#!/usr/bin/env bash
# _agent-session-tmux — host one agent session in a dedicated tmux server.
#
# The server is a systemd service, not a child of the terminal, so losing the terminal
# only detaches the client. The runtime still enters through _agent-session-admission, preserving
# the existing agent.slice confinement and its per-session resource scope.
set -uo pipefail

SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
STATE_DIR="${AGENT_SESSIONS_DIR:-$HOME/.local/state/agent-sessions}"
SOCK="${AGENT_LEDGER_MUX_SOCKET:-}"
SESSION="${AGENT_LEDGER_MUX_TARGET:-main}"
ATTACH="${AGENT_LEDGER_MUX_ATTACH:-0}"
JAILED="${AGENT_LEDGER_MUX_JAILED:-0}"
CONF="$SELF_DIR/../lib/human-session.tmux.conf"
SLICE=agent.slice
# Per-session values: they must not reach the runtime's environment, where a nested launch
# would inherit this session's socket.
unset AGENT_LEDGER_MUX_SOCKET AGENT_LEDGER_MUX_TARGET AGENT_LEDGER_MUX_ATTACH \
  AGENT_LEDGER_MUX_JAILED

note() { printf '[agent-session] %s\n' "$*" >&2; }

(( $# >= 1 )) || { note "runtime command required"; exit 64; }
[[ -n "${AGENT_LEDGER_ID:-}" && -n "$SOCK" ]] || {
  note "ledger identity or socket missing"; exit 78;
}
[[ "$AGENT_LEDGER_ID" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || {
  note "invalid ledger identity"; exit 78;
}
SOCKET_KEY="$(printf '%s' "$AGENT_LEDGER_ID" | sha256sum | cut -c1-32)"
[[ "$SESSION" == main && "$SOCK" == "$STATE_DIR/sock/$SOCKET_KEY/tmux.sock" ]] || {
  note "ledger target does not match its dedicated session path"; exit 78;
}
[[ "$ATTACH" == 0 || "$ATTACH" == 1 ]] || {
  note "invalid attach mode"; exit 78;
}
[[ "$JAILED" == 0 || "$JAILED" == 1 ]] || {
  note "invalid jail mode"; exit 78;
}

RUNTIME="$1"
shift
UNIT="agent-session-${AGENT_LEDGER_ID}.service"
SPAWN=""
STATUS="$STATE_DIR/spawn/${AGENT_LEDGER_ID}.status"
SERVER_STARTED=0

tmux_() { tmux -S "$SOCK" "$@"; }

refuse() {
  local reason="$1"
  [[ -n "$SPAWN" ]] && rm -f -- "$SPAWN"
  rm -f -- "$STATUS"
  if (( SERVER_STARTED )); then
    systemctl --user stop "$UNIT" >/dev/null 2>&1 || :
  fi
  rm -f -- "$SOCK"
  note "$reason — refusing an unhosted agent launch"
  exit 78
}

AUTHORITY=/usr/local/bin/overdeck-seat-scope-entry
[[ -x "$AUTHORITY" ]] || refuse "seat authority is not installed"
REAP_ID="$(</proc/sys/kernel/random/uuid)"
if ! node --input-type=module -e \
  'const [mod, id, name, sock, reapIdentity] = process.argv.slice(1);
   const { updateEntry } = await import(mod);
   if (!updateEntry(id, {
     mux: { kind: "tmux", socket: sock, target: name },
     tmuxSession: name,
     tmuxSocket: sock,
     tmuxReapIdentity: reapIdentity,
   })) process.exit(1);' \
  "$SELF_DIR/../lib/agent-session-reader.mjs" "$AGENT_LEDGER_ID" "$SESSION" "$SOCK" "$REAP_ID" \
  >/dev/null 2>&1; then
  refuse "tmux target could not be recorded in the ledger"
fi

AUTH_ARGS=(sudo -n "$AUTHORITY" --local-session --seat-id "$AGENT_LEDGER_ID" --socket "$SOCK" --cwd "$PWD" --reap-identity "$REAP_ID")
[[ "$ATTACH" == 1 ]] && AUTH_ARGS+=(--attach)
AUTH_ARGS+=(-- "$SELF_DIR/_agent-session-admission")
if [[ "$JAILED" == 0 ]]; then
  TMPJAIL="$(command -v tmpjail)" || {
    printf 'agent-session: tmpjail is unavailable\n' >&2
    exit 1
  }
  [[ "$TMPJAIL" == /* && -x "$TMPJAIL" ]] || {
    printf 'agent-session: tmpjail did not resolve to an absolute executable\n' >&2
    exit 1
  }
  AUTH_ARGS+=("$TMPJAIL")
fi
AUTH_ARGS+=("$RUNTIME" "$@")
exec "${AUTH_ARGS[@]}"
