#!/usr/bin/env bash
# Launch the built Atari ST example in Hatari. Defaults to PATTERN.
# Hatari autostarts the .PRG via the --auto flag; EmuTOS
# (toolchains/emulators/support/emutos-512k.img) provides the TOS ROM
# since the Ubuntu hatari package does not bundle one.
#
#   scripts/run-atarist.sh           # runs PATTERN.PRG
#   scripts/run-atarist.sh hello     # runs HELLO.PRG
#   scripts/run-atarist.sh draw      # runs DRAW.PRG
#   scripts/run-atarist.sh staxi     # runs STAXI/STAXI.PRG (Space Taxi)
#
# Argument is any built example name (case-insensitive); the script
# upper-cases it and appends .PRG, then checks the file exists.
# Aliases: "spacetaxi" -> "STAXI" (the canonical install dir name).

set -euo pipefail

if [[ $# -gt 1 ]]; then
    echo "usage: $0 [example-name]" >&2
    exit 2
fi

prog=${1:-pattern}
repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
bin_dir=$repo/build/atarist/bin

# Name aliases (input -> install/binary base name). On Atari ST the
# Space Taxi install dir + binary are "STAXI".
prog_upper=${prog^^}
case "$prog_upper" in
    SPACETAXI) prog_upper=STAXI ;;
esac
file=$prog_upper.PRG

tos=$repo/toolchains/emulators/support/emutos-512k.img

# Examples may live directly in bin_dir (PATTERN.PRG, HELLO.PRG, etc.)
# or in their own subdir alongside a per-example DATA/ tree
# (STAXI/STAXI.PRG). Prefer the subdir layout if present so STAXI
# auto-loads from its own asset bundle.
if [[ -f "$bin_dir/$prog_upper/$file" ]]; then
    auto_path="C:\\$prog_upper\\$file"
elif [[ -f "$bin_dir/$file" ]]; then
    auto_path="C:\\$file"
else
    echo "$file not built. Run 'make atarist' first." >&2
    echo "  looked for:" >&2
    echo "    $bin_dir/$prog_upper/$file" >&2
    echo "    $bin_dir/$file" >&2
    if compgen -G "$bin_dir/*.PRG" > /dev/null; then
        echo "available examples in $bin_dir:" >&2
        ls "$bin_dir"/*.PRG | xargs -n1 basename >&2
    fi
    find "$bin_dir" -maxdepth 2 -name '*.PRG' -printf '  %P\n' >&2 2>/dev/null \
        | grep '/' >&2 || true
    exit 1
fi
if [[ ! -f $tos ]]; then
    echo "TOS ROM missing: $tos" >&2
    echo "run ./toolchains/install.sh (EmuTOS should have been staged)." >&2
    exit 1
fi

# Hatari's --auto needs the target on a mounted GEMDOS drive.
exec hatari \
    --tos         "$tos" \
    --harddrive   "$bin_dir" \
    --gemdos-drive C \
    --auto        "$auto_path"
