#!/bin/bash
# Wires Supabase MCP into Hermes default profile.
# Prerequisites:
#   - New Personal Access Token (PAT) from https://supabase.com/dashboard/account/tokens
#   - Project ref(s) Rocky wants Hermes to read/write
# Usage:
#   bash supabase-mcp-wire-up.sh <PAT> [project-ref-1] [project-ref-2] ...
# Defaults to both known projects if no refs provided.

set -euo pipefail

PAT="${1:-}"
if [ -z "$PAT" ]; then
    echo "ERROR: PAT required. Get one from https://supabase.com/dashboard/account/tokens"
    echo "Usage: bash $0 <PAT> [project-ref-1] [project-ref-2] ..."
    exit 1
fi

# Default to both known projects
shift
PROJECTS=("$@")
if [ ${#PROJECTS[@]} -eq 0 ]; then
    PROJECTS=("memscjotxrzqnhrvnnkc" "eciepjpcyfurbkfzekok")
fi

echo "=== Wiring Supabase MCP into Hermes default profile ==="
echo "Projects: ${PROJECTS[*]}"

# Verify token works first
echo ""
echo "--- Verifying PAT ---"
RESP=$(curl -sS -w "\nHTTP %{http_code}" "https://api.supabase.com/v1/projects" \
    -H "Authorization: Bearer $PAT" --max-time 15)
HTTP_CODE=$(echo "$RESP" | tail -1 | awk '{print $2}')
if [ "$HTTP_CODE" != "200" ]; then
    echo "ERROR: PAT validation failed (HTTP $HTTP_CODE)"
    echo "$RESP"
    exit 2
fi
echo "PAT valid. Projects accessible via Management API."

# Wire each project's MCP server entry
for REF in "${PROJECTS[@]}"; do
    echo ""
    echo "--- Wiring project: $REF ---"
    # Hermes MCP server config — uses official @supabase/mcp-server-supabase via npx
    # --read-only for safety (can be lifted to read-write per project per Rocky's call)
    hermes mcp add "supabase-$REF" \
        --command npx \
        --args="-y" \
        --args="@supabase/mcp-server-supabase@latest" \
        --args="--read-only" \
        --args="--project-ref=$REF" \
        --env="SUPABASE_ACCESS_TOKEN=$PAT" \
        --transport stdio \
        --enabled true
    echo "MCP entry written for $REF (READ-ONLY mode)"
done

echo ""
echo "--- Restart Hermes gateway ---"
systemctl restart hermes-gateway
sleep 3

echo ""
echo "--- Verify MCP list ---"
hermes mcp list 2>&1 | head -20

echo ""
echo "=== Done ==="
echo "Test from Hermes: ask it to query supabase-$REF for 'select count(*) from auth.users'"
echo "If query fails, run: journalctl -u hermes-gateway -n 50 --no-pager"
echo ""
echo "To upgrade a project to READ-WRITE later:"
echo "  hermes mcp remove supabase-$REF"
echo "  (then re-add without --read-only flag)"
echo ""
echo "To rotate PAT (recommended every 90 days):"
echo "  1. Generate new PAT at https://supabase.com/dashboard/account/tokens"
echo "  2. Re-run this script with new PAT"
echo "  3. Revoke old PAT in dashboard"
