#!/usr/bin/env bash
# Compile a small C file with clang -target w65816 and disassemble
# the result.  Demonstrates the full toolchain front-to-back.
#
# Usage: scripts/cDemo.sh [source.c]
#   Without an argument, compiles a built-in demo program.

set -euo pipefail
source "$(dirname "$0")/common.sh"

BUILD_DIR="$TOOLS_DIR/llvm-mos-build"
CLANG="$BUILD_DIR/bin/clang"
OBJDUMP="$BUILD_DIR/bin/llvm-objdump"

[ -x "$CLANG" ]   || die "clang not built; run: ninja -C $BUILD_DIR clang"
[ -x "$OBJDUMP" ] || die "llvm-objdump not built"

src="${1:-}"
if [ -z "$src" ]; then
    src="$(mktemp --suffix=.c)"
    obj_cleanup_extra="$src"
    cat > "$src" <<'EOF'
// Built-in demo: simple integer functions
int counter;
int target = 100;

int get_counter(void)         { return counter; }
int set_counter(int v)        { counter = v; return v; }
int sum_with_target(int x)    { return x + target; }
int doubler(int x)            { return x * 2; }
unsigned half(unsigned x)     { return x / 2; }   // unsigned: uses lsr
int reset(void)               { counter = 0; return 0; }
int answer(void)              { return 42; }
EOF
    log "(no source given; using built-in demo)"
fi

obj="$(mktemp --suffix=.o)"
trap 'rm -f "$obj" ${obj_cleanup_extra:-}' EXIT

log "compiling $src with clang -target w65816 -O2"
"$CLANG" --target=w65816 -O2 -c "$src" -o "$obj"

log "disassembling result:"
echo
"$OBJDUMP" --triple=w65816 -d "$obj"
