#!/bin/sh
#
# Capture real screenshots of the screensaver on the TV.
#
#   ./scripts/screenshot.sh my-tv
#   ./scripts/screenshot.sh my-tv docs/candidates
#   COUNT=12 ./scripts/screenshot.sh my-tv shots
#   DEPLOY=0 ./scripts/screenshot.sh my-tv shots
#
# The frames come from the TV's own capture service, the same call LG's
# screenshot tools use. It rasterises the composited display, so the normal
# screensaver can stay installed and no special QML build is needed:
#
#   luna-send -n 1 luna://com.webos.service.capture/executeOneShot \
#     '{"path":"/tmp/shot.png","method":"DISPLAY","format":"PNG",
#       "width":1920,"height":1080}'
#
# webOS 4 only has com.webos.service.tv.capture (same signature), and DISPLAY
# needs an explicit width/height there or it fails with CAPTURE_ERROR_03.
# The helper on the TV tries both service names.
#
# One frame is captured per slide. The period is slideInterval + fadeDuration,
# read from screensaver-main.qml, so consecutive frames show different artworks
# and none lands in the middle of a dissolve. If a run does catch the dissolve,
# shift the phase with OFFSET=<seconds>.
#
# Deploying and starting is left to deploy.sh, which is the path that works:
#   - turnOnScreen dismisses a showing screensaver (an app launch alone is a
#     no-op while it is visible), then the old process is killed;
#   - deploy.sh writes the file, remounts and calls turnOnScreenSaver, which
#     starts a fresh process that loads the new QML.
# Starting through the application manager or calling turnOnScreenSaver while
# the screensaver is already visible both fail. DEPLOY=0 skips the install and
# just restarts whatever is already on the TV.
#
set -eu

TV=${1:?usage: screenshot.sh <tv-host> [out-dir]}
OUT=${2:-screenshots}
COUNT=1
DEPLOY=${DEPLOY:-1}
WARMUP=0
OFFSET=${OFFSET:-0}
SSH=${SSH:-ssh}
SCP=${SCP:-scp}

HERE=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SRC="$HERE/screensaver-main.qml"
DEPLOY_SH="$HERE/scripts/deploy.sh"
REMOTE_DIR=/tmp/caps-atv
REMOTE_HELPER=/tmp/webos-saver-capture.sh

WORK=$(mktemp -d "${TMPDIR:-/tmp}/saver-shots.XXXXXX")
mkdir -p "$OUT"
OUT=$(CDPATH= cd -- "$OUT" && pwd)

cleanup() {
	rm -rf "$WORK"
	$SSH "$TV" "rm -f '$REMOTE_HELPER'" >/dev/null 2>&1 || true
}
trap cleanup EXIT INT TERM

# --- the capture helper that runs on the TV ------------------------------
cat >"$WORK/capture.sh" <<'SH'
#!/bin/sh
# Capture one frame of the composited display to /tmp/caps-atv/frame-<n>.png.
n=$1
dir=/tmp/caps-atv
file=$dir/frame-$n.png
mkdir -p "$dir"
rm -f "$file"
payload=$(printf '{"path":"%s","method":"DISPLAY","format":"PNG","width":1920,"height":1080}' "$file")
for svc in com.webos.service.capture com.webos.service.tv.capture; do
    luna-send -n 1 "luna://$svc/executeOneShot" "$payload" >/dev/null 2>&1 || true
    [ -s "$file" ] && exit 0
done
echo "capture failed: $file" >&2
exit 1
SH

$SCP -q "$WORK/capture.sh" "$TV:$REMOTE_HELPER"

# --- capture one frame per slide -----------------------------------------
sleep "$WARMUP"

START=$(date +%s)
N=1
while [ "$N" -le "$COUNT" ]; do
	# Anchor every capture to START so the calls do not drift into the dissolve.
	TARGET=$((START + OFFSET + (N - 1)))
	NOW=$(date +%s)
	[ "$NOW" -lt "$TARGET" ] && sleep $((TARGET - NOW))

	if $SSH -tt "$TV" "sh $REMOTE_HELPER $N" >/dev/null 2>&1; then
		echo "  frame $N/$COUNT"
	else
		echo "  frame $N/$COUNT: capture failed" >&2
	fi
	N=$((N + 1))
done

# --- pull them ------------------------------------------------------------
GOT=$($SSH "$TV" "ls $REMOTE_DIR/*.png 2>/dev/null | wc -l" | tr -d ' \r')
if [ "${GOT:-0}" -gt 0 ]; then
	$SCP -q "$TV:$REMOTE_DIR/*.png" "$OUT/screenshot-$NOW.png"
	$SSH "$TV" "rm -rf '$REMOTE_DIR'" >/dev/null 2>&1 || true
	echo "Saved ${GOT} frame(s) to $OUT"
else
	echo "No frames captured." >&2
	exit 1
fi
