#!/usr/bin/env bash
# cua-driver-ssh: run cua-driver on a REMOTE self-hosted computer over SSH stdio.
# Use as HERMES_CUA_DRIVER_CMD for a Hermes process whose bot computer lives on another box:
#   CUA_SSH_TARGET=you@lab-box CUA_SSH_DISPLAY=12 HERMES_CUA_DRIVER_CMD=/path/cua-driver-ssh hermes ...
# Every verb Hermes uses (manifest, --help, mcp, status, check-update, call ...) is forwarded. `mcp`/`call`/
# `status` get `--socket /run/hermes-display/$CUA_SSH_DISPLAY/cua.sock` so they attach to that display's
# daemon (which already has the right DISPLAY / session bus / Chrome profile on the remote side).
# `manifest` output is rewritten so Hermes spawns THIS wrapper for MCP, not the remote binary path locally.
set -euo pipefail
: "${CUA_SSH_TARGET:?set CUA_SSH_TARGET=user@host}"
N="${CUA_SSH_DISPLAY:?set CUA_SSH_DISPLAY=<display number>}"
KEY="${CUA_SSH_IDENTITY:-$HOME/.ssh/hermes_studio_ed25519}"
REMOTE_CUA="${CUA_SSH_REMOTE_CMD:-.local/bin/cua-driver}"   # relative to the remote $HOME (ssh starts there)
SOCK="/run/hermes-display/$N/cua.sock"
SSH=(ssh -T -i "$KEY" -o IdentitiesOnly=yes -o BatchMode=yes -o ServerAliveInterval=15 -o ServerAliveCountMax=3
     -o ControlMaster=auto -o "ControlPath=${XDG_RUNTIME_DIR:-/tmp}/cua-ssh-%C" -o ControlPersist=300 "$CUA_SSH_TARGET")
q() { printf '%q ' "$@"; }

case "${1:-}" in
  manifest)
    "${SSH[@]}" "$(q "$REMOTE_CUA" "$@")" | SELF="$(readlink -f "$0")" python3 -c '
import json, os, sys
m = json.load(sys.stdin)
m.setdefault("mcp_invocation", {})["command"] = os.environ["SELF"]
json.dump(m, sys.stdout)'
    ;;
  mcp|call|status|recording|sessions|stop)
    verb="$1"; shift
    # --socket may already be present (Hermes private daemon); only add ours when absent.
    if [[ " $* " == *" --socket "* ]]; then exec "${SSH[@]}" "$(q "$REMOTE_CUA" "$verb" "$@")"; fi
    exec "${SSH[@]}" "$(q "$REMOTE_CUA" "$verb" "$@" --socket "$SOCK")"
    ;;
  *)
    exec "${SSH[@]}" "$(q "$REMOTE_CUA" "$@")"
    ;;
esac
