#!/usr/bin/env bash
# Bind the shim's durable birth row to the PID that carries this launch until it exits.
# Direct launches exec the runtime; authority-hosted launches exec their lifecycle authority.
set -u

if (( $# == 0 )); then
  printf '_agent-session-runtime: command required\n' >&2
  exit 64
fi

BIN_DIR="$(cd "$(dirname "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd)"
if [[ -n "${AGENT_LEDGER_ID:-}" && "${AGENT_LEDGER_OWN_ID:-}" == "$AGENT_LEDGER_ID" ]]; then
  if [[ ! -r "$BIN_DIR/../lib/agent-session-reader.mjs" ]] ||
    ! node --input-type=module -e '
      const [mod, ledgerId, pid, muxSocket, muxTarget, reapIdentity] = process.argv.slice(1);
      const { pidStartTicks, updateEntry } = await import(mod);
      const numericPid = Number(pid);
      const startTicks = pidStartTicks(numericPid);
      if (!Number.isInteger(startTicks)) process.exit(1);
      const patch = { pid: numericPid, pidStartTicks: startTicks };
      const muxValues = [muxSocket, muxTarget, reapIdentity];
      if (muxValues.some(Boolean)) {
        if (!muxValues.every(Boolean) || !muxSocket.startsWith("/") ||
            !/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/.test(muxTarget) ||
            !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(reapIdentity)) {
          process.exit(1);
        }
        patch.mux = { kind: "tmux", socket: muxSocket, target: muxTarget };
        patch.tmuxSession = muxTarget;
        patch.tmuxSocket = muxSocket;
        patch.tmuxReapIdentity = reapIdentity;
      }
      if (!updateEntry(ledgerId, patch)) process.exit(1);
    ' "$BIN_DIR/../lib/agent-session-reader.mjs" "$AGENT_LEDGER_ID" "$$" \
      "${AGENT_LEDGER_BIND_MUX_SOCKET:-}" "${AGENT_LEDGER_BIND_MUX_TARGET:-}" \
      "${AGENT_LEDGER_BIND_MUX_REAP_ID:-}" >/dev/null 2>&1; then
    printf '_agent-session-runtime: could not bind durable session identity — refusing launch\n' >&2
    exit 75
  fi
fi

unset AGENT_LEDGER_BIND_MUX_SOCKET AGENT_LEDGER_BIND_MUX_TARGET AGENT_LEDGER_BIND_MUX_REAP_ID
exec "$@"
