#!/usr/bin/env bash
# Launch the built DOS example in DOSBox. Defaults to PATTERN.
#
#   scripts/run-dos.sh           # runs PATTERN
#   scripts/run-dos.sh hello     # runs HELLO
#   scripts/run-dos.sh draw      # runs DRAW
#
# Argument is any built example name (case-insensitive); the script
# upper-cases it and appends .EXE, then checks the file exists.

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/dos/bin
conf=$repo/scripts/dosbox-386sx16.conf
file=${prog^^}.EXE
appdir=${prog^^}

# Two layouts supported:
#   1. New: bin/<APP>/<APP>.EXE (with DATA/ alongside it)
#      DOSBox mounts bin/<APP> as C: so DATA/foo.bin is reachable
#      via the relative path the binary opens.
#   2. Old: bin/<APP>.EXE (no DATA, or DATA at bin/DATA)
#      DOSBox mounts bin/ as C: as before.
if [[ -f "$bin_dir/$appdir/$file" ]]; then
    mount_dir="$bin_dir/$appdir"
elif [[ -f "$bin_dir/$file" ]]; then
    mount_dir="$bin_dir"
else
    echo "Neither $bin_dir/$appdir/$file nor $bin_dir/$file built." >&2
    echo "Run 'make dos' first." >&2
    if compgen -G "$bin_dir/*.EXE" > /dev/null; then
        echo "available top-level binaries:" >&2
        ls "$bin_dir"/*.EXE 2>/dev/null | xargs -n1 basename >&2
    fi
    if compgen -G "$bin_dir/*/*.EXE" > /dev/null; then
        echo "available app-dir binaries:" >&2
        ls "$bin_dir"/*/*.EXE 2>/dev/null | xargs -n1 -I{} sh -c 'dirname {} | xargs basename'
    fi
    exit 1
fi

# mouse_capture=seamless is required for DOSBox-Staging when running
# inside a VM whose host already manages the pointer; without it the
# default capture-on-click behavior fights the VM's grab and mouse
# input is unusable. On plain DOSBox this -set flag is unknown and is
# logged once as a warning, then ignored -- harmless either way.
#
# -conf $conf locks the CPU to a simulated 386SX-16 (the slowest
# realistic 386 desktop). DOSBox layers configs: anything not set in
# our file falls back to the user's main dosbox.conf.
dosboxArgs=(
    -conf "$conf"
    -set "mouse_capture=seamless"
)
# CYCLES=max (or any other DOSBox cycles value, e.g. CYCLES=50000)
# overrides the conf's period-correct 386SX-16 cap. Use this to
# A/B test whether perf ceilings are coming from the simulated CPU
# or the code itself. Same pattern as run-agi.sh.
if [[ -n "${CYCLES:-}" ]]; then
    dosboxArgs+=(-set "cpu cycles=$CYCLES")
fi
dosboxArgs+=(
    -c "C:"
    -c "$file"
    -c "pause"
    --exit "$mount_dir"
)
exec dosbox "${dosboxArgs[@]}"
