#!/usr/bin/env bash
# build.sh — compile + link + omfEmit one of the Phase 2.7 cxxSmoke probes.
#
# Usage:  bash tests/cxxSmoke/build.sh <basename>
#         tests/cxxSmoke/<basename>.cpp  ->  tests/cxxSmoke/<basename>.omf
#
# This mirrors demos/buildGno.sh exactly but reads from tests/cxxSmoke/
# instead of demos/.  Keeping the recipe local prevents demos/buildGno.sh
# from picking the test sources up via any future auto-discovery
# refactor, and lets the smoke harness invoke the test build without
# touching demos/.
#
# All five smoke probes are C++17 (structured bindings + fold expressions
# require it) — clang's default for the w65816 triple is gnu++17 today,
# which is fine.  -std=c++17 is set explicitly here as belt-and-braces in
# case the upstream default ever moves.

set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

[ $# -ge 1 ] || { echo "usage: $0 <basename>" >&2; exit 2; }
BASE="$1"

SRC="$SCRIPT_DIR/$BASE.cpp"
[ -f "$SRC" ] || { echo "no source: $SRC" >&2; exit 2; }

CC="$ROOT/tools/llvm-mos-build/bin/clang++"
LINK="$ROOT/tools/link816"
OMF="$ROOT/tools/omfEmit"
RT="$ROOT/runtime"

OBJ="$SCRIPT_DIR/$BASE.o"
BIN="$SCRIPT_DIR/$BASE.bin"
MAP="$SCRIPT_DIR/$BASE.map"
RELOC="$SCRIPT_DIR/$BASE.reloc"
OUT="$SCRIPT_DIR/$BASE.omf"

echo "compile: $(basename "$SRC") -> $BASE.o"
"$CC" --target=w65816 -std=c++17 \
    -I"$RT/include" -I"$RT/include/c++" \
    -O2 -ffunction-sections -fno-exceptions -fno-rtti \
    -c "$SRC" -o "$OBJ"

echo "link: -> $BASE.bin"
"$LINK" -o "$BIN" --text-base 0x1000 --bss-base 0xA000 \
    --map "$MAP" --reloc-out "$RELOC" \
    "$RT/crt0Gno.o" "$OBJ" \
    "$RT/libcGno.o" "$RT/gnoKernel.o" "$RT/gnoGsos.o" \
    "$RT/libc.o" "$RT/snprintf.o" "$RT/extras.o" \
    "$RT/softFloat.o" "$RT/softDouble.o" \
    "$RT/math.o" \
    "$RT/iigsToolbox.o" "$RT/iigsToolboxExtra.o" \
    "$RT/libgcc.o" \
    "$RT/libcxxabi.o" "$RT/libcxxabiSjlj.o"

echo "OMF: -> $BASE.omf"
"$OMF" --input "$BIN" --map "$MAP" \
    --base 0x1000 --entry __start --output "$OUT" \
    --name "$(echo "$BASE" | tr '[:lower:]' '[:upper:]' | cut -c1-8)" \
    --expressload --relocs "$RELOC" --stack-size "${GNO_STACK_SIZE:-0x4000}"

ls -la "$OUT"
echo "done: $OUT"
