#!/usr/bin/env bash
# Grab the GAME's image, not the emulator window.
#
# Every pixel oracle in this toolkit (at_menu, at_title, wait_not_black, the
# HUD readers) was measured against a bare 1280x720 game image. xenia's window
# is a GTK window with a menu bar, so the game surface actually starts ~25 px
# down — and when it does, all of those constants read the wrong pixels. That
# is not a hypothetical: a run sat on a plainly visible MAIN MENU for 300 s
# reporting "no main menu", and a later one missed the title screen entirely and
# let the attract movie loop for ten minutes.
#
# The offset is not guessed: it is the xenia window's height minus 720. So this
# works whether or not the menu bar is there, and needs no per-display constant.
# Put this directory first on PATH and existing scripts keep working unchanged.
set -u
REAL=/usr/local/bin/screenshot
OUT="${1:-}"
if [ -z "$OUT" ]; then
  dir="${HOME:-/tmp}/shots"; mkdir -p "$dir"
  n_file="$dir/.counter"; n=$(( $(cat "$n_file" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$n_file"
  OUT="$dir/shot-$(printf '%04d' "$n").png"
fi

RAW="$(mktemp /tmp/shot-raw-XXXXXX.png)"
trap 'rm -f "$RAW"' EXIT
"$REAL" "$RAW" >/dev/null || exit 1

# "…": ("xenia_canary" "Xenia_canary")  1280x745+0+0  +0+0
geo=$(xwininfo -root -children 2>/dev/null \
      | grep '"xenia_canary"' | grep -oE '[0-9]+x[0-9]+\+-?[0-9]+\+-?[0-9]+' | head -1)
if [ -z "$geo" ]; then           # no window found — hand back the raw grab
  cp "$RAW" "$OUT"; echo "$OUT"; exit 0
fi
W=${geo%%x*}; rest=${geo#*x}; H=${rest%%+*}; rest=${rest#*+}; X=${rest%%+*}; Y=${rest#*+}
OFF=$(( H - 720 )); [ "$OFF" -lt 0 ] && OFF=0
TOP=$(( Y + OFF ))
[ "$TOP" -lt 0 ] && TOP=0
if [ "$OFF" -eq 0 ] && [ "$TOP" -eq 0 ] && [ "$X" -eq 0 ]; then
  cp "$RAW" "$OUT"; echo "$OUT"; exit 0
fi
# Height is whatever is still on screen: a 1280x745 window on a 720-high root
# loses its last rows, and every oracle point in use sits well above them.
convert "$RAW" -crop "${W}x720+${X}+${TOP}" +repage "$OUT" 2>/dev/null \
  || cp "$RAW" "$OUT"
echo "$OUT"
