#!/usr/bin/env bash
# build.sh - compile a demo C source into a GS/OS-loadable OMF.
#
# Usage: bash demos/build.sh <basename>
#   where demos/<basename>.c is the source.  Output is
#   demos/<basename>.omf in the same directory.
#
# Uses crt0Gsos (the GS/OS-aware crt) and ExpressLoad-wrapped multi-
# seg OMF so the slow-Loader rejection path is avoided.  The OMF
# launches via runViaFinder.sh after cadius-injection onto the GS/OS
# data disk.

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

[ $# -ge 1 ] || { echo "usage: $0 <basename>" >&2; exit 2; }
BASE="$1"
SRC="$SCRIPT_DIR/$BASE.c"
[ -f "$SRC" ] || { echo "no source: $SRC" >&2; exit 2; }

CLANG="$PROJECT_ROOT/tools/llvm-mos-build/bin/clang"
LINK="$PROJECT_ROOT/tools/link816"
OMF="$PROJECT_ROOT/tools/omfEmit"

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: $BASE.c -> $BASE.o"
"$CLANG" --target=w65816 -I"$PROJECT_ROOT/runtime/include" \
    -O2 -ffunction-sections -c "$SRC" -o "$OBJ"

echo "link: -> $BASE.bin"
# bss-base 0xA000 keeps BSS above the SHR shadow region ($2000-$9FFF
# in bank 0 mirrors to bank E1 SHR memory).  Without this, the smaller
# section-gc'd demos place BSS at e.g. $2300 and global writes scribble
# on the screen.
"$LINK" -o "$BIN" --text-base 0x1000 --bss-base 0xA000 \
    --map "$MAP" --reloc-out "$RELOC" \
    "$PROJECT_ROOT/runtime/crt0Gsos.o" "$OBJ" \
    "$PROJECT_ROOT/runtime/libc.o" \
    "$PROJECT_ROOT/runtime/snprintf.o" \
    "$PROJECT_ROOT/runtime/extras.o" \
    "$PROJECT_ROOT/runtime/softFloat.o" \
    "$PROJECT_ROOT/runtime/softDouble.o" \
    "$PROJECT_ROOT/runtime/iigsGsos.o" \
    "$PROJECT_ROOT/runtime/iigsToolbox.o" \
    "$PROJECT_ROOT/runtime/desktop.o" \
    "$PROJECT_ROOT/runtime/libgcc.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"

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