#!/usr/bin/env bash
# Boot to the TITLE MENU and stop there — no save is loaded.
#
# nav_probe.sh's boot half deliberately loads a save, which is wrong for any
# experiment that wants to *inspect* save slots rather than enter one: with
# several probe saves on disc the load picks one of them, and a probe value the
# game cannot make sense of turns into a long "NOW PROCESSING" (or a mission
# load, if a d-pad step is dropped and A lands on TAKE OFF).
#
# From the main menu, LOAD GAME is one d-pad step away and its slot list renders
# every slot's Details panel — STAGE, Game Status, Points, Times Cleared — which
# is read straight out of each save's payload. That makes this the cheap harness
# for save-field probes: write N slots, boot once, arrow through them.
#
# Run as ONE BLOCKING FOREGROUND call. Usage: boot_menu.sh [tag]
set -u
export HOME=/sylph-home/re SDL_AUDIODRIVER=dummy DISPLAY=:98
SD="$(cd "$(dirname "$0")" && pwd)"
SHOTS=/sylph-home/re/shots
TAG="${1:-menu}"
mkdir -p "$SHOTS"

alive(){ ps -o pid=,stat= -C xenia_canary 2>/dev/null | awk '$2 !~ /^Z/ {print $1}'; }
ensure_display(){
  if ! xdpyinfo -display "$DISPLAY" >/dev/null 2>&1; then
    rm -f "/tmp/.X${DISPLAY#:}-lock" 2>/dev/null || true
    nohup bash -c 'Xvfb "$0" -screen 0 1280x720x24 -ac -nolisten tcp \
        +extension GLX +extension RANDR >/tmp/xvfb98.log 2>&1' "$DISPLAY" </dev/null >/dev/null 2>&1 &
    for _ in $(seq 1 50); do xdpyinfo -display "$DISPLAY" >/dev/null 2>&1 && break; sleep 0.2; done
    nohup env DISPLAY="$DISPLAY" HOME=/sylph-home openbox </dev/null >/tmp/openbox98.log 2>&1 &
    sleep 1
  fi
  xdpyinfo -display "$DISPLAY" >/dev/null 2>&1 || { echo "DISPLAY UNAVAILABLE"; exit 1; }
}

[ -n "$(alive)" ] && { kill -9 $(alive) 2>/dev/null; sleep 2; }
rm -f /dev/shm/xenia_memory_* /dev/shm/xenia_code_cache_* 2>/dev/null
ensure_display
cd /sylph-home/re
nohup run-canary --audio --apu=sdl --log_mask=13 \
  --logged_profile_slot_0_xuid=E0300000EFBEA3D4 </dev/null >/dev/null 2>&1 &
sleep 5
"$SD/skip_intro.sh" 600 || { echo "BOOT FAILED (skip_intro exit $?)"; exit 1; }
sleep 14
screenshot "$SHOTS/$TAG-menu.png" >/dev/null 2>&1
echo "AT MAIN MENU (cursor on NEW GAME); LOAD GAME is one d-pad step down"
