#!/bin/bash
# install-gws-mcp.sh — set up shared Google Workspace MCP servers as launchd services.
#
# One always-on streamable-http server per Google account, fixed port each,
# so any number of Claude Code sessions share one process, one token cache,
# and one OAuth callback port (no per-session stdio spawns, no port races).
#
# Reads accounts from ~/.config/google/gws-accounts.conf (name port email secret).
# Idempotent: safe to re-run after editing the conf. Portable: only uses $HOME.
#
# Usage: bash install-gws-mcp.sh [--conf PATH]
set -euo pipefail

CONF="${HOME}/.config/google/gws-accounts.conf"
[ "${1:-}" = "--conf" ] && CONF="$2"
REPO="${HOME}/Developer/google_workspace_mcp"
# Upstream. The 2026-08-31 private-mirror repoint was reverted same day: upstream
# implemented send-as alias support natively (from_email tool param, per-alias
# signature selection), so the local patch aa66dc7 is obsolete and nothing is carried.
REPO_URL="https://github.com/taylorwilsdon/google_workspace_mcp.git"
LABEL_PREFIX="co.remixrevenue.gws"
LOGDIR="${HOME}/Library/Logs/gws-mcp"
UID_N=$(id -u)

[ -f "$CONF" ] || { echo "ERROR: accounts conf not found at $CONF"; exit 1; }

# 1. Server code + venv (uv bootstraps its own python if the OS one is too old)
if [ ! -d "$REPO" ]; then
  echo "Cloning google_workspace_mcp..."
  git clone --depth 1 "$REPO_URL" "$REPO"
fi
if [ ! -x "$REPO/.venv/bin/python" ]; then
  echo "Building venv..."
  if ! command -v uv >/dev/null && [ ! -x "$HOME/.local/bin/uv" ]; then
    curl -LsSf https://astral.sh/uv/install.sh | sh
  fi
  UV="$(command -v uv || echo "$HOME/.local/bin/uv")"
  (cd "$REPO" && "$UV" venv .venv --python 3.11 && "$UV" pip install -e . --python .venv/bin/python)
fi

# 2. Kill any legacy per-session stdio instances
pkill -f "google_workspace_mcp/main.py" 2>/dev/null || true
sleep 1

mkdir -p "$LOGDIR" "$HOME/Library/LaunchAgents"

# 3. One launchd service per account
grep -Ev '^\s*(#|$)' "$CONF" | while read -r name port email secret; do
  secret_path="$HOME/.config/google/$secret"
  [ -f "$secret_path" ] || { echo "SKIP $name: missing $secret_path"; continue; }
  mkdir -p "$HOME/.google_workspace_mcp/credentials/$name"
  plist="$HOME/Library/LaunchAgents/${LABEL_PREFIX}-${name}.plist"
  cat > "$plist" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
  <key>Label</key><string>${LABEL_PREFIX}-${name}</string>
  <key>ProgramArguments</key><array>
    <string>${REPO}/.venv/bin/python</string>
    <string>${REPO}/main.py</string>
    <string>--tools</string><string>drive</string><string>docs</string><string>sheets</string>
    <string>gmail</string><string>calendar</string><string>slides</string>
    <string>--single-user</string>
    <string>--transport</string><string>streamable-http</string>
  </array>
  <key>WorkingDirectory</key><string>${REPO}</string>
  <key>EnvironmentVariables</key><dict>
    <key>GOOGLE_CLIENT_SECRETS</key><string>${secret_path}</string>
    <key>USER_GOOGLE_EMAIL</key><string>${email}</string>
    <key>WORKSPACE_MCP_CREDENTIALS_DIR</key><string>${HOME}/.google_workspace_mcp/credentials/${name}</string>
    <key>PORT</key><string>${port}</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>StandardOutPath</key><string>${LOGDIR}/${name}.log</string>
  <key>StandardErrorPath</key><string>${LOGDIR}/${name}.err.log</string>
</dict></plist>
EOF
  launchctl bootout "gui/${UID_N}/${LABEL_PREFIX}-${name}" 2>/dev/null || true
  sleep 1
  launchctl bootstrap "gui/${UID_N}" "$plist" || { sleep 2; launchctl bootstrap "gui/${UID_N}" "$plist"; }
  echo "started ${name} on :${port} (${email})"
done

# 4. Verify every port answers MCP
sleep 5
grep -Ev '^\s*(#|$)' "$CONF" | while read -r name port email secret; do
  [ -f "$HOME/.config/google/$secret" ] || continue
  code=$(curl -s -o /dev/null -w "%{http_code}" -m 5 -X POST "http://localhost:${port}/mcp" \
    -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
    -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}' || echo "000")
  echo "verify ${name} :${port} -> HTTP ${code}"
done

echo "Done. Point clients at http://localhost:PORT/mcp. First tool call per un-authed account returns an OAuth URL to click once."
