#!/usr/bin/env bash
# Headless UBER perf capture for the Atari ST (Hatari).
#
# Runs build/atarist/bin/UBER.PRG under Hatari (fast-forward, no sound)
# on a private Xvfb display, polling joeylog.txt until UBER prints its
# "press any key to exit" completion marker (or a wall-clock timeout),
# then kills the emulator.
#
# UBER writes "UBER: <op>: N iters / M frames = K ops/sec" lines to
# joeylog.txt in its CWD == the GEMDOS drive C: == the bin dir, so the
# log lands directly in build/atarist/bin/joeylog.txt where
# tools/uber-perf-table expects it.
#
#   scripts/bench-atarist.sh             # default 90s timeout
#   TIMEOUT=120 scripts/bench-atarist.sh # override
#
# NOTE: requires the ST supervisor-mode fix in src/atarist/hal.c
# (jlpInit Super(0L)); without it UBER bus-errors on the first present.

set -euo pipefail

repo=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
bin_dir=$repo/build/atarist/bin
tos=$repo/toolchains/emulators/support/emutos-512k.img
log=$bin_dir/joeylog.txt
timeout_s=${TIMEOUT:-90}

if [[ ! -f $bin_dir/UBER.PRG ]]; then
    echo "UBER.PRG not built. Run 'make atarist' first." >&2
    exit 1
fi
if [[ ! -f $tos ]]; then
    echo "TOS ROM missing: $tos" >&2
    exit 1
fi

rm -f "$log"

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

echo "bench-atarist: running UBER headless (timeout ${timeout_s}s)..." >&2
DISPLAY=$display hatari \
    --tos          "$tos" \
    --harddrive    "$bin_dir" \
    --gemdos-drive C \
    --drive-a off --drive-b off \
    --sound        off \
    --fast-forward on \
    --frameskips   4 \
    --auto         "C:\\UBER.PRG" >/tmp/bench-atarist-hatari.log 2>&1 &
hat_pid=$!

# Poll for the completion marker UBER flushes just before its key wait.
waited=0
while (( waited < timeout_s )); do
    if [[ -f $log ]] && grep -q "press any key to exit" "$log"; then
        break
    fi
    sleep 1
    (( waited++ )) || true
done

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

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-atarist: WARNING -- timed out before completion marker (partial capture)" >&2
fi
echo "bench-atarist: captured $ops op lines (complete=$done_marker) in ${waited}s" >&2
echo "  -> $log" >&2
grep "UBER:" "$log" | sed 's/ | hash=.*//' || true
