#!/usr/bin/env bash
# sylph-run.sh — run the ours xenia-rs emulator N times and report the standard
# intro-video oracles. Inherits any XENIA_* probe knobs from the caller's env
# (e.g. XENIA_FORCE_TID=24, XENIA_STARVE_LIMIT=16, XENIA_LOG_SIGNAL=0x40d10214).
#
# Usage:  [XENIA_*=... ] sylph-run.sh [runs] [n_instr] [timeout_s] [extra_grep_regex]
#   runs        default 6
#   n_instr     default 3000000000
#   timeout_s   default 180   (boot is DETERMINISTIC and reaches the intro
#                 movie's first on-screen frame at ~81s wall; the movie then
#                 plays reliably. The old 90s default sat ~9s above that point,
#                 so host-load wall-clock jitter cut some runs off just before
#                 the movie — the apparent "~1/3 of runs" flakiness. 180s clears
#                 it with margin. Guest-instruction execution is identical run
#                 to run; only wall time varies with host speed.)
#   extra_grep  optional ERE; matching stdout lines are saved per-run for ad-hoc inspection
#
# Always-on oracles: source-read 0x824ff708 count (>1 = feeder looped), decode-worker
# resumes (tid25 start_entry 0x82506588 / tid26 0x825065b8). Full per-run log kept under
# /tmp/sylph-run/.
set -u
cd "/home/fabi/RE - Project Sylpheed/xenia-rs" || exit 2
RUNS="${1:-6}"; N="${2:-3000000000}"; TO="${3:-180}"; XGREP="${4:-}"
OUT=/tmp/sylph-run; mkdir -p "$OUT"
BIN=./target/release/xenia-rs
[ -x "$BIN" ] || { echo "build first: (cd xenia-rs && export CARGO_BUILD_JOBS=4 && cargo build --release)"; exit 3; }

echo "sylph-run: runs=$RUNS n=$N timeout=${TO}s  knobs=[$(env | grep -oE 'XENIA_[A-Z_]+=[^ ]*' | tr '\n' ' ')]"
for i in $(seq 1 "$RUNS"); do
  F="$OUT/run_$i.log"; REC="$OUT/rec_$i.txt"
  RUST_LOG="${RUST_LOG:-warn,xenia_kernel::exports=info,xenia_kernel::state=info}" \
    XENIA_DISPATCH_REC=1 XENIA_DISPATCH_REC_SITES="${XENIA_DISPATCH_REC_SITES:-0x824ff708}" \
    XENIA_DISPATCH_REC_OUT="$REC" \
    timeout "$TO" "$BIN" exec sylpheed.iso -n "$N" >"$F" 2>&1
  pkill -x xenia-rs 2>/dev/null
  sc=$(grep 0x824ff708 "$REC" 2>/dev/null | awk '{print $3}' | head -1)
  w25=$(grep -c "RESUME.*0x82506588" "$F" 2>/dev/null)
  w26=$(grep -c "RESUME.*0x825065b8" "$F" 2>/dev/null)
  xg=""; [ -n "$XGREP" ] && xg="  match($XGREP)=$(grep -cE "$XGREP" "$F" 2>/dev/null)"
  reached="movie"; [ "${sc:-0}" = "0" ] && reached="no-movie"
  echo "  run $i: [$reached] source-read=${sc:-0}  tid25-resume=$w25 tid26-resume=$w26$xg   (log: $F)"
done
echo "done. per-run logs in $OUT/. Reliable: source-read>1 = feeder looped; tid25/26 resume = pipeline progressed."
