#!/usr/bin/env bash
# ft-eyes-session: record the eye cameras and SteamVR's gaze together, for SECONDS (default 10),
# as a new recording NAME in ~/.local/share/frametop/eyes/captures (FT_EYES_CAPTURES).
# Usage: gaze/tracker/lab/ft-eyes-session NAME [SECONDS]
#
#   frames.raw, index.txt, clocks.txt   every eye-camera frame (ft-eyes-record, from the shared
#                                       frames of frametop-eyegrab.service; no root)
#   gaze.jsonl                          ft-gaze's samples (gaze/build/ft-gaze)
# Both are timed on CLOCK_MONOTONIC_RAW ("t" in gaze.jsonl, the last column of index.txt).
set -euo pipefail
lab=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
repo=$(cd "$lab/../../.." && pwd)
name=${1:?usage: ft-eyes-session NAME [SECONDS]}
secs=${2:-10}
out=${FT_EYES_CAPTURES:-$HOME/.local/share/frametop/eyes/captures}/$name
[ -e "$out" ] && { echo "$out exists" >&2; exit 1; }

# ft-gaze runs in the dev container; start it first, it takes a moment to connect. It quits
# when its stdin closes (--watch-stdin): killing distrobox doesn't reach it in the container.
# The recorder makes the folder; ft-gaze's output waits for it.
tmp=$(mktemp -d)
sleep $((secs + 3)) | "$HOME/.local/bin/distrobox" enter dev -- "$repo/gaze/build/ft-gaze" \
  --watch-stdin > "$tmp/gaze.jsonl" 2> "$tmp/gaze.log" &
gaze=$!
sleep 2
python3 "$lab/ft-eyes-record" "$name" "$secs"
wait $gaze || true
mv "$tmp/gaze.jsonl" "$tmp/gaze.log" "$out/"
rmdir "$tmp"
echo "$(wc -l < "$out/index.txt") frames, $(wc -l < "$out/gaze.jsonl") gaze samples in $out"
