#!/usr/bin/env bash
# Headless UBER perf capture for DOS (DOSBox, 386SX-16 timing).
#
# Mounts build/dos/bin as C: in a headless DOSBox (Xvfb), runs UBER.EXE
# (which writes JOEYLOG.TXT to its CWD == C: == the host bin dir), polls
# that log for UBER's "press any key to exit" completion marker, then
# kills DOSBox. tools/uber-perf-table reads build/dos/bin/JOEYLOG.TXT.
#
# Uses the same dosbox-386sx16.conf as run-dos.sh so the cycle budget
# matches the PERF.md reference machine.
#
#   scripts/bench-dos.sh             # default 90s timeout
#   TIMEOUT=120 scripts/bench-dos.sh # override

set -euo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
bin_dir=$repo/build/dos/bin
conf=$repo/scripts/dosbox-386sx16.conf
log=$bin_dir/JOEYLOG.TXT
timeout_s=${TIMEOUT:-90}

if [[ ! -f $bin_dir/UBER.EXE ]]; then
    echo "UBER.EXE not built. Run 'make dos' first." >&2
    exit 1
fi

rm -f "$log" "$bin_dir/joeylog.txt"

display=:$((90 + RANDOM % 9))
Xvfb "$display" -screen 0 800x600x24 -nolisten tcp >/dev/null 2>&1 &
xvfb_pid=$!
sleep 0.4
cleanup() {
    kill "$dosbox_pid" 2>/dev/null || true
    kill "$xvfb_pid"   2>/dev/null || true
    wait 2>/dev/null || true
}
trap cleanup EXIT

echo "bench-dos: running UBER headless (timeout ${timeout_s}s)..." >&2
DISPLAY=$display dosbox \
    -conf "$conf" \
    -c "C:" \
    -c "UBER.EXE" \
    "$bin_dir" >/tmp/bench-dos-dosbox.log 2>&1 &
dosbox_pid=$!

waited=0
while (( waited < timeout_s )); do
    if [[ -f $log ]] && grep -q "press any key to exit" "$log" 2>/dev/null; then
        break
    fi
    sleep 1
    (( waited++ )) || true
done

if [[ ! -f $log ]]; then
    echo "bench-dos: FAIL -- no JOEYLOG.TXT produced" >&2
    exit 1
fi

# uber-perf-table reads build/dos/bin/JOEYLOG.TXT directly (uppercase).
ops=$(grep -c "ops/sec" "$log" || true)
done_marker=$(grep -c "press any key to exit" "$log" || true)
if (( done_marker == 0 )); then
    echo "bench-dos: WARNING -- timed out before completion marker (partial capture)" >&2
fi
echo "bench-dos: captured $ops op lines (complete=$done_marker) in ${waited}s" >&2
echo "  -> $log" >&2
grep "UBER:" "$log" | sed 's/ | hash=.*//' || true
