#!/usr/bin/env bash
# ============================================================
# sentinel-mcp-server-keychain (macOS)
#
# Reads the API key from macOS Keychain instead of plaintext
# config. Exports the key and launches the MCP server in
# stdio mode.
#
# First-time setup (run once):
#   security add-generic-password -s sentinel-mcp-server -a api-key -w YOUR_KEY
#
# MCP client config (claude_desktop_config.json):
#   {
#     "mcpServers": {
#       "sentinel": {
#         "command": "sentinel-mcp-server-keychain",
#         "env": {
#           "SENTINEL_GATEWAY_URL": "https://your-gateway-url.com"
#         }
#       }
#     }
#   }
#
# No SENTINEL_API_KEY in the config file — the keychain provides it.
# ============================================================

set -euo pipefail

# ── Read API key from macOS Keychain ──
KEY=$(security find-generic-password -s sentinel-mcp-server -a api-key -w 2>/dev/null)

if [ -z "$KEY" ]; then
  echo "ERROR: API key not found in macOS Keychain." >&2
  echo "" >&2
  echo "Store your key first:" >&2
  echo "  security add-generic-password -s sentinel-mcp-server -a api-key -w YOUR_API_KEY" >&2
  echo "" >&2
  echo "To update an existing key:" >&2
  echo "  security delete-generic-password -s sentinel-mcp-server -a api-key 2>/dev/null" >&2
  echo "  security add-generic-password -s sentinel-mcp-server -a api-key -w NEW_API_KEY" >&2
  exit 1
fi

export SENTINEL_API_KEY="$KEY"
export MCP_TRANSPORT="stdio"

# ── Find and exec the main binary ──
# Works whether installed globally (npm -g) or from tarball
SELF_DIR="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}" 2>/dev/null || echo "${BASH_SOURCE[0]}")")" && pwd)"

if [ -f "$SELF_DIR/sentinel-mcp-server" ]; then
  # Tarball layout: bin/ contains both scripts
  exec "$SELF_DIR/sentinel-mcp-server" "$@"
elif command -v sentinel-mcp-server &>/dev/null; then
  # Global npm install: sentinel-mcp-server is on PATH
  exec sentinel-mcp-server "$@"
else
  echo "ERROR: sentinel-mcp-server not found." >&2
  echo "Install it first: npm install -g sentinel-mcp-server" >&2
  exit 1
fi
