#!/usr/bin/env bash
# M4 demand-paging buffer-pool gate. Pure C (NOT elb/elc). Writes only under /tmp.
# Runs the suite twice: an -O2 correctness build and an ASan+UBSan build.
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
SRC="$HERE/../../lang/runtime/engram_store.c"
TST="$HERE/test_bufpool.c"

echo "== compiling (gcc -O2): test_bufpool.c engram_store.c =="
BIN="/tmp/test_bufpool.$$"
gcc -O2 -Wall -Wextra -std=c11 "$TST" "$SRC" -o "$BIN"
"$BIN"; rc=$?
rm -f "$BIN"; rm -rf /tmp/engram-bufpool-test-*
[ $rc -ne 0 ] && exit $rc

echo
echo "== ASan+UBSan build (memory-error + UB checks; LSan unavailable on macOS) =="
ABIN="/tmp/test_bufpool_asan.$$"
gcc -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -std=c11 "$TST" "$SRC" -o "$ABIN"
ASAN_OPTIONS=detect_leaks=0 UBSAN_OPTIONS=halt_on_error=1 "$ABIN"; rc=$?
rm -f "$ABIN"; rm -rf /tmp/engram-bufpool-test-*
exit $rc
