#!/bin/bash

set -e

pipenv run python testit.py

# testit.py regenerates main.c, a harness that asserts every offset and size the
# python model claims against what the compiler actually lays out. Building and
# running it is the only check that the model matches C, so it is part of the
# test rather than an optional extra.
CC=${CC:-gcc}
OUT=${TMPDIR:-/tmp}/xctype_check

if ! command -v "$CC" >/dev/null 2>&1; then
    echo "error: '$CC' not found, cannot validate the model against a C compiler." >&2
    echo "       install a C compiler or set CC to one." >&2
    exit 1
fi

"$CC" -Wall -Wextra -Wformat -Werror -o "$OUT" main.c
"$OUT"

# Optional 32 bit cross check. On a 32 bit target uint64_t is not unsigned long
# and alignment rules differ, so this catches what x86-64 never shows. Opt in by
# pointing ARM_GCC at a cross compiler, for example:
#   ARM_GCC=/opt/toolchains/arm-none-eabi-gcc/xpack-arm-none-eabi-gcc-14.2.1-1.1/bin/arm-none-eabi-gcc ./run_test
if [ -n "$ARM_GCC" ]; then
    "$ARM_GCC" -mcpu=cortex-m33 -mthumb -Wall -Wextra -Wformat -Werror -c main.c -o "$OUT.o"
    echo "cross check ok: $("$ARM_GCC" -dumpmachine) accepts the generated layout"
fi
