#!/usr/bin/env bash
# agent-eyes — work the headless Hyprland session from the outside.
#
#   agent-eyes status                       is the session up, can I reach it?
#   agent-eyes shot [--out FILE]            grab one frame of the screen
#   agent-eyes run [--] CMD [ARGS...]       launch a GUI app INTO the session
#   agent-eyes record --seconds N [--out F] film whatever happens
#
# The session itself is a system service (hyprland-headless +
# hyprland-headless-stream, see the flake's NixOS module). This script is the
# *consumer* side of docs/CONTRACT.md: it never starts a compositor.
#
# Access: the runtime directory is 0750 and the socket 0660, both group
# `hhstream`. If this process cannot read them it re-execs itself under
# `sg hhstream -c ...`, which is the only reliable fix for a login that
# predates the group membership.
set -euo pipefail

SOCKET=${AGENT_EYES_SOCKET:-/run/hypr-stream/stream.sock}
RUNDIR=$(dirname "$SOCKET")
GROUP=${AGENT_EYES_GROUP:-hhstream}
CLIENT=${AGENT_EYES_CLIENT:-hhstream-client}
SHOT_DIR=${AGENT_EYES_SHOT_DIR:-/var/lib/hermes/public/agent-eyes}

die() { printf 'agent-eyes: %s\n' "$*" >&2; exit 1; }
have_group() { [ -x "$RUNDIR" ] && [ -r "$SOCKET" ]; }

# Only the setuid wrapper can switch groups, and PATH order decides which `sg`
# you get. A login shell has /run/wrappers/bin first and works; a cron job's
# PATH reaches the non-setuid copy in the system profile instead, which dies
# with "setgroups: Operation not permitted" — and, with stderr going to
# /dev/null, that looks like "chromium exited immediately". So pick the wrapper
# deliberately rather than trusting PATH.
sg_bin() {
  local c
  for c in /run/wrappers/bin/sg "$(command -v sg 2>/dev/null || true)"; do
    [ -n "$c" ] && [ -x "$c" ] && [ -u "$c" ] && { printf '%s\n' "$c"; return 0; }
  done
  return 1
}

# One self re-exec, so every branch below may assume group access.
if ! have_group; then
  SG=$(sg_bin) || die "cannot join group $GROUP: no setuid 'sg' found (looked in /run/wrappers/bin)"
  exec "$SG" "$GROUP" -c "$(printf '%q ' "$0" "$@")"
fi

wayland_socket() {
  local s
  for s in "$RUNDIR"/wayland-?; do
    [ -S "$s" ] && { printf '%s\n' "$s"; return 0; }
  done
  return 1
}

usage() { sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; }

cmd_status() {
  local svc
  echo "services:"
  for svc in hyprland-headless hyprland-headless-stream; do
    printf '  %-28s %s\n' "$svc" "$(systemctl is-active "$svc" 2>&1 || true)"
  done
  printf 'socket:    %s\n' "$SOCKET"
  printf 'access:    %s\n' "$([ -r "$SOCKET" ] && echo "readable (group $GROUP)" || echo DENIED)"
  local wl
  wl=$(wayland_socket) || wl=""
  printf 'wayland:   %s\n' "${wl:-none found}"
  printf 'probe:     '
  if "$CLIENT" --socket "$SOCKET" --count 1 --timeout 5 --out /dev/null 2>&1 | tail -1; then
    :
  else
    echo "no frame — compositor or capture tool is down"
    return 1
  fi
}

cmd_shot() {
  local out="$SHOT_DIR/latest.jpg"
  while [ $# -gt 0 ]; do
    case $1 in
      --out) out=${2:?--out needs a path}; shift 2 ;;
      *) die "shot: unknown argument '$1'" ;;
    esac
  done
  mkdir -p "$(dirname "$out")"
  "$CLIENT" --socket "$SOCKET" --count 1 --out "$out" >/dev/null
  printf '%s\n' "$out"
}

# Launch a GUI client into the running compositor. Window rules, wallpaper and
# gaps are whatever the session's hyprland.conf says; a new window just appears.
cmd_run() {
  [ $# -gt 0 ] || die "run: needs a command (e.g. agent-eyes run chromium)"
  [ "${1:-}" = "--" ] && shift
  local wl
  wl=$(wayland_socket) || die "run: no wayland socket in $RUNDIR"
  XDG_RUNTIME_DIR="$RUNDIR" \
  WAYLAND_DISPLAY="${wl##*/}" \
  XDG_SESSION_TYPE=wayland \
    exec "$@"
}

cmd_record() {
  local seconds=10 out=agent-eyes.mp4 keep=0
  while [ $# -gt 0 ]; do
    case $1 in
      --seconds) seconds=${2:?--seconds needs a number}; shift 2 ;;
      --out) out=${2:?--out needs a path}; shift 2 ;;
      --keep) keep=1; shift ;;
      *) die "record: unknown argument '$1'" ;;
    esac
  done
  command -v ffmpeg >/dev/null || die "record: ffmpeg not on PATH"

  local dir
  dir=$(mktemp -d "${TMPDIR:-/tmp}/agent-eyes-rec.XXXXXX")
  local got
  got=$(python3 - "$SOCKET" "$dir" "$seconds" <<'PY'
import json, os, socket, sys, time

sock_path, outdir, seconds = sys.argv[1], sys.argv[2], float(sys.argv[3])
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(sock_path)
f = s.makefile("rb")
hello = json.loads(f.readline())
ext = "jpg" if hello["format"].endswith("jpeg") else "png"

def read_exactly(n):
    buf = b""
    while len(buf) < n:
        chunk = f.read(n - len(buf))
        if not chunk:
            raise EOFError
        buf += chunk
    return buf

start = time.monotonic()
n = 0
while True:
    line = f.readline()
    if not line:
        break
    size = int(line.strip())
    payload = read_exactly(size)
    n += 1
    with open(os.path.join(outdir, "frame-%05d.%s" % (n, ext)), "wb") as out:
        out.write(payload)
    if time.monotonic() - start >= seconds:
        break

elapsed = time.monotonic() - start
# The encoder gets the *measured* rate, so the video plays at true speed even
# though a software-rendered VM tops out well under the advertised fps.
print("%d %d %.3f %s" % (n, round(n / elapsed) if elapsed else 1, elapsed, ext))
PY
)
  set -- $got
  local frames=$1 fps=$2 elapsed=$3 ext=$4
  [ "$frames" -gt 0 ] || die "record: read no frames in ${seconds}s"
  ffmpeg -hide_banner -loglevel error -y \
    -framerate "$fps" -i "$dir/frame-%05d.$ext" \
    -c:v libx264 -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" \
    -map_metadata -1 -fflags +bitexact -flags:v +bitexact \
    "$out"
  printf '%s (%s frames in %ss -> %s fps)\n' "$out" "$frames" "$elapsed" "$fps"
  [ "$keep" = 1 ] || rm -rf "$dir"
}

[ $# -gt 0 ] || { usage; exit 1; }
sub=$1; shift
case $sub in
  status|st)  cmd_status "$@" ;;
  shot)       cmd_shot "$@" ;;
  run)        cmd_run "$@" ;;
  record|rec) cmd_record "$@" ;;
  help|-h|--help) usage ;;
  *) die "unknown subcommand '$sub' (try: status, shot, run, record, help)" ;;
esac
