#!/usr/bin/env bash
# One-time setup for the internal Vend Claude marketplace.
# Usage:  curl -fsSL https://<host>/bootstrap.sh | bash
# Or:     bash <(curl -fsSL https://<host>/bootstrap.sh)
set -euo pipefail

SERVICE_URL="https://plugin-marketplace.m10s.io"
# Cloud Run IAM validates the JWT audience against the canonical *.run.app URL
# even when the request comes in via a custom domain.
TOKEN_AUDIENCE="https://claude-marketplace-207000833221.europe-north1.run.app"
SA="claude-marketplace-user@vend-plugin-marketplace.iam.gserviceaccount.com"

bail() { echo "error: $*" >&2; exit 1; }

command -v gcloud  >/dev/null || bail "gcloud not installed — see https://cloud.google.com/sdk/docs/install"
command -v git     >/dev/null || bail "git not installed"
command -v claude  >/dev/null || bail "claude CLI not in PATH"

if ! gcloud auth list --filter=status:ACTIVE --format='value(account)' | grep -q '@vend\.com$'; then
  bail "no active @vend.com gcloud account — run: gcloud auth login"
fi

echo "→ minting Bearer token for $SERVICE_URL"
TOKEN=$(gcloud auth print-identity-token \
  --impersonate-service-account="$SA" \
  --audiences="$TOKEN_AUDIENCE" \
  --include-email)

echo "→ writing private git include (~/.config/marketplace-auth/git-headers.gitconfig, mode 0600)"
mkdir -p ~/.config/marketplace-auth
chmod 700 ~/.config/marketplace-auth
( umask 077
  cat > ~/.config/marketplace-auth/git-headers.gitconfig <<EOF
[http "$SERVICE_URL/"]
	extraheader = Authorization: Bearer $TOKEN
EOF
)

# Idempotent: skip if already registered
if ! git config --global --get-all include.path 2>/dev/null \
     | grep -qxF "$HOME/.config/marketplace-auth/git-headers.gitconfig"; then
  git config --global --add include.path "$HOME/.config/marketplace-auth/git-headers.gitconfig"
  echo "→ registered git include.path"
fi

echo "→ adding marketplace"
claude plugin marketplace add "$SERVICE_URL/marketplace.git" >/dev/null
echo "→ installing marketplace-auth helper (refreshes token on every Claude Code start)"
claude plugin install marketplace-auth@vend-plugins >/dev/null

cat <<'DONE'

✔ done.

Restart Claude Code so the marketplace-auth SessionStart hook can run.
After that, the token refreshes automatically on every session start —
no manual steps needed.

Install plugins normally:
  claude plugin install <plugin-name>@vend-plugins
DONE
