#!/usr/bin/env bash
# Build + link + run the Lua smoke test under MAME.
set -eu
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
CLANG="$PROJECT_ROOT/tools/llvm-mos-build/bin/clang"
LINK="$PROJECT_ROOT/tools/link816"
LUA_OBJ="$SCRIPT_DIR/build"
RT="$PROJECT_ROOT/runtime"

cd "$SCRIPT_DIR"

# Ensure Lua is built.
if [ ! -d "$LUA_OBJ" ] || [ -z "$(ls $LUA_OBJ/*.o 2>/dev/null)" ]; then
    bash "$SCRIPT_DIR/build.sh"
fi

# Build the test wrapper.
"$CLANG" -target w65816 -O2 -ffunction-sections \
    -I "$RT/include" -I "$SCRIPT_DIR/lua-5.1.5/src" \
    -c luaTest.c -o luaTest.o

# Link with full runtime + all Lua objects + the test.  Multi-segment
# layout: text packs into 48KB chunks starting in bank 0, additional
# segments at bank 1+.
"$LINK" -o luaTest.bin --text-base 0x1000 \
    --segment-cap 0xB000 \
    --segment-bank-base 0x040000 \
    --manifest luaTest.manifest.json \
    "$RT/crt0.o" \
    "$RT/libc.o" "$RT/libgcc.o" "$RT/softFloat.o" "$RT/softDouble.o" \
    "$RT/math.o" "$RT/strtol.o" "$RT/snprintf.o" "$RT/sscanf.o" \
    "$RT/qsort.o" "$RT/strtok.o" "$RT/timeExt.o" "$RT/extras.o" \
    $LUA_OBJ/*.o luaTest.o

ls -la luaTest*.bin luaTest*.json 2>&1 | head
echo ""
echo "Running under MAME (this may take longer than typical smoke tests —"
echo "Lua interpretation overhead is significant on a 1 MHz IIgs)..."

# Lua interp is slow — give it plenty of frames.  Multi-segment program
# needs the runMultiSeg.sh loader (reads the manifest, places each
# segment at its declared bank-aligned address).  Image paths in the
# manifest are relative to the script's directory.
MAME_CHECK_FRAME=1200 MAME_SECS=30 MAME_TIMEOUT=180 MAME_RAMSIZE=8M \
    bash "$PROJECT_ROOT/scripts/runMultiSeg.sh" \
        "$SCRIPT_DIR/luaTest.manifest.json" \
        0x025000 c0de
