#!/usr/bin/env bash
# Poll the framebuffer for the "PRESS (A) BUTTON" title screen (the green A glyph
# at ~625,618) and tap A the instant it appears — the title auto-returns to the
# attract loop after a few seconds, which is why a human-paced tap misses it.
set -u
export HOME=/sylph-home/re
TMP=/tmp/title-probe.png
deadline=$(( SECONDS + ${1:-900} ))
while [ $SECONDS -lt $deadline ]; do
  if screenshot "$TMP" >/dev/null 2>&1; then
    read -r r g b < <(convert "$TMP" -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 detected (rgb $r,$g,$b) at ${SECONDS}s — tapping A"
      vgamepad tap A 200
      exit 0
    fi
  fi
  sleep 1
done
echo "TIMEOUT: title not seen"
exit 1
