#!/bin/zsh

set -euo pipefail

PKCS11_LIB="${PKCS11_LIB:-/usr/local/lib/opensc-pkcs11.so}"
TOKEN_HOST="${TOKEN_HOST:-operator-access-token.svc.ad1.r2}"
SSH_CONFIG_FILE="${SSH_CONFIG_FILE:-$HOME/.ssh/config.oci}"
OCI_BIN="${OCI_BIN:-/opt/homebrew/bin/oci}"
OCI_SESSION_REGION="${OCI_SESSION_REGION:-us-chicago-1}"
OCI_PROFILE_NAME="${OCI_PROFILE_NAME:-DEFAULT}"
OCI_SESSION_VALIDATE_TIMEOUT_SECONDS="${OCI_SESSION_VALIDATE_TIMEOUT_SECONDS:-2}"
RESET_AGENT="${RESET_AGENT:-0}"
DEDICATED_AGENT_PID=""
DEDICATED_AGENT_SOCK=""

log() {
  print -u2 -- "$@"
}

cleanup() {
  if [[ -n "${DEDICATED_AGENT_PID}" && -n "${DEDICATED_AGENT_SOCK}" ]]; then
    SSH_AGENT_PID="${DEDICATED_AGENT_PID}" SSH_AUTH_SOCK="${DEDICATED_AGENT_SOCK}" ssh-agent -k >/dev/null 2>&1 || true
  fi
}

run_oci() {
  "${OCI_BIN}" --profile "${OCI_PROFILE_NAME}" "$@"
}

resolve_timeout_bin() {
  local candidate

  for candidate in timeout gtimeout /opt/homebrew/bin/timeout /opt/homebrew/bin/gtimeout; do
    if [[ "${candidate}" == /* ]]; then
      if [[ -x "${candidate}" ]]; then
        print -r -- "${candidate}"
        return 0
      fi
      continue
    fi

    if command -v "${candidate}" >/dev/null 2>&1; then
      command -v "${candidate}"
      return 0
    fi
  done

  return 1
}

get_validate_timeout_seconds() {
  local timeout_seconds="${OCI_SESSION_VALIDATE_TIMEOUT_SECONDS}"

  if [[ ! "${timeout_seconds}" =~ '^[0-9]+([.][0-9]+)?$' ]]; then
    log "Warning: invalid OCI_SESSION_VALIDATE_TIMEOUT_SECONDS=${timeout_seconds}; using 2 seconds."
    print -r -- "2"
    return 0
  fi

  print -r -- "${timeout_seconds}"
}

run_oci_with_timeout() {
  local timeout_seconds="$1"
  shift

  local timeout_bin
  if ! timeout_bin="$(resolve_timeout_bin)"; then
    log "Warning: no timeout binary found; running OCI command without a timeout."
    run_oci "$@"
    return $?
  fi

  "${timeout_bin}" "${timeout_seconds}" "${OCI_BIN}" --profile "${OCI_PROFILE_NAME}" "$@"
}

ensure_oci_session() {
  if [[ ! -x "${OCI_BIN}" ]]; then
    print -u2 "OCI CLI not found or not executable: ${OCI_BIN}"
    exit 1
  fi

  local validate_timeout_seconds
  validate_timeout_seconds="$(get_validate_timeout_seconds)"

  set +e
  run_oci_with_timeout "${validate_timeout_seconds}" session validate >/dev/null 2>&1
  local validate_rc=$?
  set -e

  if [[ ${validate_rc} -eq 0 ]]; then
    log "OCI CLI session is already valid."
    return 0
  fi

  if [[ ${validate_rc} -eq 124 ]]; then
    log "OCI CLI session validation timed out after ${validate_timeout_seconds} seconds; treating session as invalid."
  fi

  log "OCI CLI session is not valid; attempting refresh."
  set +e
  run_oci session refresh >/dev/null 2>&1
  local refresh_rc=$?
  set -e

  if [[ ${refresh_rc} -eq 0 ]]; then
    log "OCI CLI session refresh succeeded."
    return 0
  fi

  log "Running OCI CLI session authenticate for ${OCI_SESSION_REGION} with profile ${OCI_PROFILE_NAME}."
  "${OCI_BIN}" session authenticate --region "${OCI_SESSION_REGION}" --profile-name "${OCI_PROFILE_NAME}"
}

ensure_ssh_agent() {
  log "Starting dedicated ssh-agent for Codex."
  unset SSH_AUTH_SOCK SSH_AGENT_PID
  eval "$(ssh-agent -s)" >/dev/null
  DEDICATED_AGENT_PID="${SSH_AGENT_PID:-}"
  DEDICATED_AGENT_SOCK="${SSH_AUTH_SOCK:-}"
}

add_pkcs11_provider() {
  log "Loading PKCS#11 provider: ${PKCS11_LIB}"
  ssh-add -s "${PKCS11_LIB}" >/dev/null
}

prepare_agent() {
  ensure_ssh_agent
  add_pkcs11_provider
}

if [[ ! -f "${SSH_CONFIG_FILE}" ]]; then
  print -u2 "SSH config file not found: ${SSH_CONFIG_FILE}"
  exit 1
fi

if [[ "${RESET_AGENT}" == "1" ]]; then
  log "Resetting SSH agent on explicit request."
  pkill -9 ssh-agent >/dev/null 2>&1 || true
  pkill -9 ssh-pkcs11-helper >/dev/null 2>&1 || true
  sleep 1
fi

trap cleanup EXIT INT TERM

ensure_oci_session

prepare_agent

log "Refreshing OPERATOR_ACCESS_TOKEN from ${TOKEN_HOST} using ${SSH_CONFIG_FILE}"
export OPERATOR_ACCESS_TOKEN="$(ssh -F "${SSH_CONFIG_FILE}" "${TOKEN_HOST}" "generate --mode jwt")"
export OP_TOKEN="${OPERATOR_ACCESS_TOKEN}"

log "Using fresh OP_TOKEN for Codex and DevOps MCP."

/opt/homebrew/bin/codex "$@"
