#!/usr/bin/env bash
# In-container entrypoint for one harness seat. Seeds credentials from the read-only
# /seed mount into the tmpfs HOME, then execs the WRAPPER-CONTRACT wrapper unchanged.
#
# Exit codes are the wrapper's own — this file never invents one except 2 (its own
# usage error). exec means the wrapper's rc is the container's rc.
set -uo pipefail

WRAPPER="" WORKSPACE="" TASK_SLUG="" MODEL="" TIMEOUT="" PROFILE="" PERMISSION_MODE="" RESUME="" THREAD_ID="" LOG_DIR=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --wrapper)   WRAPPER="${2:-}";   shift 2;;
    --workspace) WORKSPACE="${2:-}"; shift 2;;
    --task-slug) TASK_SLUG="${2:-}"; shift 2;;
    --model)     MODEL="${2:-}";     shift 2;;
    --timeout)   TIMEOUT="${2:-}";   shift 2;;
    --profile)   PROFILE="${2:-}";   shift 2;;
    --permission-mode)
      [[ $# -ge 2 && -n "${2:-}" && -z "$PERMISSION_MODE" ]] \
        || { echo '{"ok":false,"detail":"seat-entrypoint: --permission-mode requires one value"}' >&2; exit 2; }
      PERMISSION_MODE="$2"; shift 2;;
    --resume)    RESUME="${2:-}";    shift 2;;
    --thread-id) THREAD_ID="${2:-}"; shift 2;;
    --log-dir)   LOG_DIR="${2:-}";   shift 2;;
    *) echo "{\"ok\":false,\"detail\":\"seat-entrypoint: unknown arg $1\"}" >&2; exit 2;;
  esac
done

[[ -n "$TASK_SLUG" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: --task-slug required"}' >&2; exit 2; }
[[ -z "$PERMISSION_MODE" || "$PERMISSION_MODE" == "safe" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: --permission-mode safe required"}' >&2; exit 2; }
[[ "$TASK_SLUG" != incident-* || "$PERMISSION_MODE" == "safe" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: incident dispatch requires --permission-mode safe"}' >&2; exit 2; }
[[ -x "$WRAPPER" || -f "$WRAPPER" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: wrapper missing in workspace mount"}' >&2; exit 2; }
[[ -d "$WORKSPACE" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: workspace missing"}' >&2; exit 2; }
[[ -f /seed/prompt.txt ]] || { echo '{"ok":false,"detail":"seat-entrypoint: /seed/prompt.txt missing"}' >&2; exit 2; }
[[ "$(command -v git 2>/dev/null || true)" == /usr/local/bin/git ]] && git --deny-gate-selftest \
  || { echo '{"ok":false,"detail":"seat-entrypoint: git deny gate unavailable"}' >&2; exit 12; }

# Its own tmpfs, not a subdir of /tmp: codex refuses to create its PATH helper binaries when
# CODEX_HOME resolves under a temporary directory, and warns on every run.
export HOME=/seat-home
mkdir -p "$HOME" || { echo '{"ok":false,"detail":"seat-entrypoint: HOME tmpfs not writable"}' >&2; exit 2; }
chmod 0700 "$HOME"
# claude runs as uid 0 in here and refuses --permission-mode bypassPermissions without this.
export IS_SANDBOX=1

AUTHORITY_MODE="${HARNESS_SEAT_AUTHORITY_MODE:-}"
if [[ -n "$AUTHORITY_MODE" ]]; then
  [[ "$AUTHORITY_MODE" == subrouter ]] || { echo '{"ok":false,"detail":"seat-entrypoint: unsupported authority mode"}' >&2; exit 2; }
  AUTHORITY_ORIGIN="${HARNESS_SEAT_AUTHORITY_ORIGIN:-}"
  AUTHORITY_PROVIDER="${HARNESS_SEAT_AUTHORITY_PROVIDER:-}"
  AUTHORITY_NAME="${HARNESS_SEAT_AUTHORITY_NAME:-}"
  AUTHORITY_PROBE_ONLY="${HARNESS_SEAT_AUTHORITY_PROBE_ONLY:-0}"
  [[ "$AUTHORITY_PROVIDER" == codex || "$AUTHORITY_PROVIDER" == claude ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority provider invalid"}' >&2; exit 2; }
  [[ "$AUTHORITY_NAME" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority name invalid"}' >&2; exit 2; }
  [[ "$AUTHORITY_PROBE_ONLY" == 0 || "$AUTHORITY_PROBE_ONLY" == 1 ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority probe mode invalid"}' >&2; exit 2; }
  if [[ "$AUTHORITY_ORIGIN" =~ ^http://100\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3}):31416$ ]]; then
    [[ ${BASH_REMATCH[1]} -ge 64 && ${BASH_REMATCH[1]} -le 127 && ${BASH_REMATCH[2]} -le 255 && ${BASH_REMATCH[3]} -le 255 ]] \
      || { echo '{"ok":false,"detail":"seat-entrypoint: authority origin invalid"}' >&2; exit 2; }
  else
    echo '{"ok":false,"detail":"seat-entrypoint: authority origin invalid"}' >&2; exit 2
  fi
  [[ -f /seed/subrouter/route.id && ! -L /seed/subrouter/route.id ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority route missing"}' >&2; exit 2; }
  [[ -f /seed/subrouter/proxy.key && ! -L /seed/subrouter/proxy.key ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority grant missing"}' >&2; exit 2; }
  IFS= read -r AUTHORITY_ROUTE_ID < /seed/subrouter/route.id || true
  [[ "$AUTHORITY_ROUTE_ID" =~ ^[A-Za-z0-9_-]{12,96}$ ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority route invalid"}' >&2; exit 2; }
  SUBROUTER_PROXY_KEY="$(< /seed/subrouter/proxy.key)"
  [[ -n "$SUBROUTER_PROXY_KEY" && "$SUBROUTER_PROXY_KEY" != *[[:space:]]* ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority grant invalid"}' >&2; exit 2; }
  unset HARNESS_SEAT_CREDENTIALS_MANIFEST
  export SUBROUTER_SESSION_ID="seat-${TASK_SLUG}-$$"
  export SUBROUTER_PROVIDER="$AUTHORITY_PROVIDER"
  if [[ "$AUTHORITY_PROVIDER" == codex ]]; then
    export CODEX_HOME="$HOME"
    export CODEX_SQLITE_HOME="$HOME/sqlite"
    export SUBROUTER_PROXY_KEY
    mkdir -p "$CODEX_SQLITE_HOME"
    cat > "$CODEX_HOME/config.toml" <<EOF
model_provider = "subrouter"

[model_providers.subrouter]
name = "Subrouter"
base_url = "${AUTHORITY_ORIGIN}/r/${AUTHORITY_ROUTE_ID}/v1"
env_key = "SUBROUTER_PROXY_KEY"
wire_api = "responses"
EOF
    chmod 0600 "$CODEX_HOME/config.toml"
  else
    export CLAUDE_CONFIG_DIR="$HOME"
    export ANTHROPIC_BASE_URL="${AUTHORITY_ORIGIN}/r/${AUTHORITY_ROUTE_ID}"
    export ANTHROPIC_AUTH_TOKEN="$SUBROUTER_PROXY_KEY"
  fi
  # The credentialless acceptance path proves the real seat/container/network seam without
  # invoking a provider. Status is authenticated by the same per-run grant the agent would use.
  if [[ "$AUTHORITY_PROBE_ONLY" == 1 ]]; then
    STATUS_URL="${AUTHORITY_ORIGIN}/r/${AUTHORITY_ROUTE_ID}/_subrouter/status"
    code="$(curl -sS -o /tmp/subrouter-seat-status.json -w '%{http_code}' \
      -H "Authorization: Bearer $SUBROUTER_PROXY_KEY" -H 'Accept: application/json' "$STATUS_URL" || true)"
    [[ "$code" == 200 ]] || { echo '{"ok":false,"detail":"seat-entrypoint: authority status probe failed"}' >&2; exit 3; }
    jq -e '.state == "migration-required" or .state == "ready"' /tmp/subrouter-seat-status.json >/dev/null \
      || { echo '{"ok":false,"detail":"seat-entrypoint: authority status payload invalid"}' >&2; exit 3; }
    jq -c '{ok:true,authority_mode:"subrouter",provider:.provider,state:.state,route_fingerprint:.route_fingerprint,grant_fingerprint:.grant_fingerprint}' \
      /tmp/subrouter-seat-status.json
    exit 0
  fi
else
  # Native/unmigrated seats keep the provider credential copy path until their own cutover.
  seed_copy() {
    local src="$1" dest="$2"
    [[ -f "$src" ]] || return 0
    mkdir -p "$(dirname "$dest")" && install -m 0600 "$src" "$dest"
  }
  CREDENTIALS_MANIFEST="${HARNESS_SEAT_CREDENTIALS_MANIFEST:-}"
  [[ -n "$CREDENTIALS_MANIFEST" && -f "$CREDENTIALS_MANIFEST" ]] || { echo '{"ok":false,"detail":"seat-entrypoint: credential manifest missing from bundled runtime"}' >&2; exit 2; }
  while IFS=$'\t' read -r cred_home cred_seed; do
    [[ -n "$cred_home" ]] && seed_copy "$cred_seed" "$HOME/$cred_home"
  done < <(jq -r '.items[] | [.home, .seed] | @tsv' "$CREDENTIALS_MANIFEST")
fi

export HARNESS_SEAT_CONTAINER=1
export TMPDIR=/tmp
[[ -n "$LOG_DIR" ]] && { mkdir -p "$LOG_DIR" || { echo '{"ok":false,"detail":"seat-entrypoint: log dir not writable"}' >&2; exit 2; }; export HARNESS_LOG_DIR="$LOG_DIR"; }

PROMPT="$(< /seed/prompt.txt)"

ARGS=("$WRAPPER" --workspace "$WORKSPACE" --trust "$PROMPT" --task-slug "$TASK_SLUG")
[[ -n "$MODEL" ]]     && ARGS+=(--model "$MODEL")
[[ -n "$TIMEOUT" ]]   && ARGS+=(--timeout "$TIMEOUT")
[[ -n "$PROFILE" ]]   && ARGS+=(--profile "$PROFILE")
[[ -n "$PERMISSION_MODE" ]] && ARGS+=(--permission-mode "$PERMISSION_MODE")
[[ -n "$RESUME" ]]    && ARGS+=(--resume "$RESUME")
[[ -n "$THREAD_ID" ]] && ARGS+=(--thread-id "$THREAD_ID")

cd "$WORKSPACE" || { echo '{"ok":false,"detail":"seat-entrypoint: cd workspace failed"}' >&2; exit 2; }
exec bash "${ARGS[@]}" < /dev/null
