#!/usr/bin/env bash
# Drive the boot sequence to the main menu without a human in the loop.
#  - movie playing  (two grabs 0.6s apart differ a lot) -> tap A to skip
#  - static screen  -> if the green "PRESS (A) BUTTON" glyph is there, tap A and stop
# Static logo screens are left alone, so a stray tap can never land on NEW GAME.
set -u
export HOME=/sylph-home/re
# The X root keeps the DEAD session's last frame, so a fresh launch would be
# detected as "already at the title". Blank it, and wait for the new window.
xsetroot -solid black 2>/dev/null || true
until xdotool search --name "Xenia-canary" >/dev/null 2>&1; do sleep 1; done
deadline=$(( SECONDS + ${1:-900} ))
while [ $SECONDS -lt $deadline ]; do
  screenshot /tmp/f1.png >/dev/null 2>&1; sleep 0.6
  screenshot /tmp/f2.png >/dev/null 2>&1
  d=$(compare -metric RMSE /tmp/f1.png /tmp/f2.png null: 2>&1 | sed 's/ .*//' | cut -d. -f1)
  d=${d:-0}
  read -r r g b < <(convert /tmp/f2.png -format "%[fx:int(255*p{625,618}.r)] %[fx:int(255*p{625,618}.g)] %[fx:int(255*p{625,618}.b)]" info:)
  if [ "$g" -gt 130 ] && [ $((g - r)) -gt 45 ] && [ $((g - b)) -gt 45 ]; then
    echo "TITLE at ${SECONDS}s -> A"; vgamepad tap A 250; exit 0
  fi
  if [ "$d" -gt 1500 ]; then
    echo "movie (rmse $d) at ${SECONDS}s -> skip A"; vgamepad tap A 250; sleep 3
  fi
  sleep 1
done
echo "TIMEOUT"; exit 1
