#!/usr/bin/env bash
# ONE blocking session: boot -> Stage 02 in flight -> sweep the view and press
# F10 several times, so each press dumps xenia_ship_capture_NN.log with whatever
# capital ships are on screen at that moment.
#
# Why a sweep and not a single press: the 2026-07-26 e106 capture missed the
# bridge because it was culled at that camera angle. Several presses at
# different headings cost nothing (the capture is a one-frame draw dump) and
# each one is independently correlatable.
#
# Usage: ship_capture_session.sh [presses] [out_dir]
set -u
export HOME=/sylph-home/re SDL_AUDIODRIVER=dummy DISPLAY=:98
SD="$(cd "$(dirname "$0")" && pwd)"
PRESSES="${1:-6}"
OUT="${2:-/sylph-home/re/shipcap}"
BINDIR="/home/fabi/RE - Project Sylpheed/xenia-canary-native/build/bin/Linux/Release"
SHOTS=/sylph-home/re/shots
mkdir -p "$OUT" "$SHOTS"

rm -f "$BINDIR"/xenia_ship_capture_*.log

"$SD/launch_mission.sh" fly || { echo "BOOT FAILED"; exit 1; }

# F10 goes to the emulator window through XTEST; the window must be focused.
win="$(xdotool search --class -- xenia | tail -1)"
[ -z "$win" ] && win="$(xdotool search --name -- Xenia | tail -1)"
echo "WINDOW=$win"
[ -n "$win" ] && { xdotool windowactivate "$win" 2>/dev/null; xdotool windowfocus "$win" 2>/dev/null; }

for i in $(seq 1 "$PRESSES"); do
  screenshot "$SHOTS/shipcap-$i.png" >/dev/null 2>&1
  if [ -n "$win" ]; then xdotool key --window "$win" F10; else xdotool key F10; fi
  sleep 3
  # Yaw a little between presses so a culled part gets another chance, and the
  # craft keeps closing on the friendly formation (the capital ships).
  vgamepad axis LX 0.45; sleep 1.2; vgamepad axis LX 0.0
  sleep 3
done

sleep 2
cp -v "$BINDIR"/xenia_ship_capture_*.log "$OUT"/ 2>/dev/null
cp -v "$SHOTS"/shipcap-*.png "$OUT"/ 2>/dev/null
grep -c '^DRAW' "$OUT"/xenia_ship_capture_*.log 2>/dev/null
echo "CAPTURE SESSION DONE"
