#!/usr/bin/env bash
# Agent self-serve smoke path (CLI track) for docs/developers/agent-quickstart.md
#
# Verifies bootstrap/setup against a live IDP. Human AAL2 approval (step 4) is
# never automated. Secrets are never printed: use --json and inspect offline.
#
# Usage:
#   export SIGID_IDP=http://auth.sigid.localhost:3000   # or https://auth.sigid.org
#   bash docs/developers/agent-quickstart.sh
#   bash docs/developers/agent-quickstart.sh --through-delegation-create
#   bash docs/developers/agent-quickstart.sh --help
#
set -euo pipefail

SIGID_IDP="${SIGID_IDP:-https://auth.sigid.org}"
AGENT_NAME="${AGENT_NAME:-quickstart-agent}"
REDIRECT_URI="${REDIRECT_URI:-http://localhost:3000/}"
DELEGATION_AUDIENCE="${DELEGATION_AUDIENCE:-sigid}"
DELEGATION_SCOPE="${DELEGATION_SCOPE:-applications:manage}"
THROUGH_DELEGATION=0
CLI=(sigid-cli)

usage() {
  cat <<'EOF'
agent-quickstart.sh – CLI self-test for the agent self-serve quickstart

Environment:
  SIGID_IDP              IDP base URL (default: https://auth.sigid.org)
  AGENT_NAME             Agent name for setup (default: quickstart-agent)
  REDIRECT_URI           OAuth redirect (default: http://localhost:3000/)
  DELEGATION_AUDIENCE    For --through-delegation-create (default: sigid)
  DELEGATION_SCOPE       For --through-delegation-create (default: applications:manage)
  SIGID_PASSPHRASE       Optional non-interactive keystore passphrase

Flags:
  --through-delegation-create  Also run delegation create (prints link only; no poll)
  --cli PATH                   Use this sigid-cli binary (default: sigid-cli on PATH)
  -h, --help                   Show this help

Does not log access tokens, refresh tokens, client secrets, or device codes.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --through-delegation-create)
      THROUGH_DELEGATION=1
      shift
      ;;
    --cli)
      CLI=("$2")
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if ! command -v "${CLI[0]}" >/dev/null 2>&1 && [[ ! -x "${CLI[0]}" ]]; then
  echo "error: ${CLI[0]} not found. Install: npx @sigid/cli --version  or cargo install --path crates/sigid-cli" >&2
  exit 1
fi

echo "==> IDP: $SIGID_IDP"
echo "==> setup --name $AGENT_NAME"

# Global --output defaults to json. Only print non-secret identifiers.
setup_tmp="$(mktemp)"
trap 'rm -f "$setup_tmp" "${del_tmp:-}"' EXIT
if ! "${CLI[@]}" --output json setup \
  --idp "$SIGID_IDP" \
  --name "$AGENT_NAME" \
  --redirect-uri "$REDIRECT_URI" \
  >"$setup_tmp" 2>/tmp/sigid-agent-quickstart-setup.err; then
  echo "error: setup failed (see /tmp/sigid-agent-quickstart-setup.err; redact before sharing)" >&2
  exit 1
fi

if command -v python3 >/dev/null 2>&1; then
  python3 - "$setup_tmp" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as f:
    d = json.load(f)
for k in (
    "agent_id",
    "organization_id",
    "organization_slug",
    "tenant_id",
    "tenant_slug",
    "tenant_issuer",
    "client_id",
    "key_label",
    "fingerprint",
):
    if d.get(k) is not None:
        print(f"{k}={d[k]}")
PY
else
  echo "setup completed; python3 missing – not dumping JSON (may contain client_secret)"
fi
rm -f /tmp/sigid-agent-quickstart-setup.err

echo "==> verify-setup"
"${CLI[@]}" verify-setup --idp "$SIGID_IDP" || {
  echo "error: verify-setup failed" >&2
  exit 1
}

if [[ "$THROUGH_DELEGATION" -eq 1 ]]; then
  echo "==> delegation create (human must open the link; this script does not poll tokens)"
  del_tmp="$(mktemp)"
  if ! "${CLI[@]}" --output json delegation create \
    --idp "$SIGID_IDP" \
    --audience "$DELEGATION_AUDIENCE" \
    --scope "$DELEGATION_SCOPE" \
    >"$del_tmp" 2>/tmp/sigid-agent-quickstart-delegation.err; then
    echo "error: delegation create failed (redact logs before sharing)" >&2
    exit 1
  fi
  if command -v python3 >/dev/null 2>&1; then
    python3 - "$del_tmp" <<'PY'
import json, sys
with open(sys.argv[1], encoding="utf-8") as f:
    d = json.load(f)
for k in (
    "absolute_link",
    "verification_uri_complete",
    "user_code_display",
    "expires_in",
    "interval",
):
    if d.get(k) is not None:
        print(f"{k}={d[k]}")
print("device_code=<redacted; take from local create JSON offline for poll>")
PY
  else
    echo "delegation create ok; python3 missing – not dumping JSON (contains device_code)"
  fi
  rm -f /tmp/sigid-agent-quickstart-delegation.err
  echo "Next: human AAL2 approve, then: sigid-cli delegation poll <device_code> --idp \"$SIGID_IDP\""
fi

echo "OK: agent quickstart self-test finished (steps 1–2${THROUGH_DELEGATION:+, 3 partial})."
echo "Steps 4–5 require a human browser and an explicit poll; not run by this script."
