#!/usr/bin/env bash
# Provision a headless agent-proxy server's credentials from THIS (browser-capable) machine.
# The interactive OAuth is done once here; only the resulting credential is shipped to the server.
#
#   deploy/provision-auth.sh codex  <ssh_target> [LOCAL_CODEX_HOME]   # ship ~/.codex/auth.json → server
#   deploy/provision-auth.sh verify <base_url> <api_key> [model]      # smoke-test a provisioned server
#
# claude needs no file copy — run `claude setup-token` here and paste the token into the server's
# .env as CLAUDE_CODE_OAUTH_TOKEN (see deploy/AUTH.md).
set -euo pipefail

cmd=${1:-}
case "$cmd" in
  codex)
    target=${2:?usage: provision-auth.sh codex <ssh_target> [LOCAL_CODEX_HOME]}
    home=${3:-$HOME/.codex}
    auth="$home/auth.json"
    [ -f "$auth" ] || { echo "✗ $auth not found — log in first:  CODEX_HOME=$home codex login"; exit 1; }
    echo "→ shipping $auth to $target:~/.codex/auth.json"
    ssh "$target" 'mkdir -p ~/.codex && chmod 700 ~/.codex'
    scp -q "$auth" "$target:.codex/auth.json"
    ssh "$target" 'chmod 600 ~/.codex/auth.json && codex login status'
    echo "✓ codex credential provisioned on $target (auto-refreshes via refresh_token)"
    ;;
  verify)
    base=${2:?usage: provision-auth.sh verify <base_url> <api_key> [model]}
    key=${3:?api key required}
    model=${4:-gpt-5.5}
    echo "→ POST $base/v1/chat/completions (model=$model)"
    curl -fsS --max-time 90 "$base/v1/chat/completions" \
      -H "x-api-key: $key" -H 'content-type: application/json' \
      -d "{\"model\":\"$model\",\"messages\":[{\"role\":\"user\",\"content\":\"Reply with exactly: pong\"}]}" \
      | (command -v jq >/dev/null && jq -r '.choices[0].message.content // .' || cat)
    echo "✓ server answered"
    ;;
  *)
    echo "usage:"
    echo "  $0 codex  <ssh_target> [LOCAL_CODEX_HOME]   ship codex auth.json to a server"
    echo "  $0 verify <base_url> <api_key> [model]      smoke-test a provisioned server"
    exit 1
    ;;
esac
