#!/bin/sh
set -eu

SERVER_NAME="barvinca"
SERVER_URL="https://mcp.barvinca.com/mcp"
SCOPES="${BARVINCA_MCP_SCOPES:-barvinca.read}"

say() {
  printf '%s\n' "$*"
}

find_codex() {
  if command -v codex >/dev/null 2>&1; then
    command -v codex
    return 0
  fi

  if [ "$(uname -s 2>/dev/null || true)" = "Darwin" ]; then
    for candidate in \
      "/Applications/ChatGPT.app/Contents/Resources/codex" \
      "/Applications/Codex.app/Contents/Resources/codex"
    do
      if [ -x "$candidate" ]; then
        printf '%s\n' "$candidate"
        return 0
      fi
    done
  fi

  return 1
}

case "$(uname -s 2>/dev/null || true)" in
  Darwin) PLATFORM="macOS" ;;
  Linux) PLATFORM="Linux" ;;
  *)
    say "This installer supports macOS and Linux."
    say "On Windows, use https://barvinca.com/install/codex.ps1"
    exit 1
    ;;
esac

if ! CODEX_BIN="$(find_codex)"; then
  say "Codex CLI was not found."
  say "Install or update Codex, sign in, and run this installer again."
  say "Codex documentation: https://learn.chatgpt.com/docs/codex"
  exit 1
fi

if ! "$CODEX_BIN" mcp add --help 2>&1 | grep -q -- '--oauth-resource'; then
  say "This Codex version is too old for Barvinca OAuth resource binding."
  say "Update Codex and run this installer again."
  exit 1
fi

say "Barvinca MCP installer for $PLATFORM"
say "Codex: $CODEX_BIN"
say "Server: $SERVER_URL"
say "Scopes: $SCOPES"

existing=""
if existing="$("$CODEX_BIN" mcp get "$SERVER_NAME" --json 2>/dev/null)"; then
  if ! printf '%s\n' "$existing" | grep -Fq "$SERVER_URL"; then
    say "A different Codex MCP server already uses the name $SERVER_NAME."
    say "Review it with: codex mcp get $SERVER_NAME --json"
    say "Remove it only if intended: codex mcp remove $SERVER_NAME"
    exit 1
  fi
  say "The Barvinca endpoint is already configured; keeping the existing entry."
else
  "$CODEX_BIN" mcp add "$SERVER_NAME" --url "$SERVER_URL" --oauth-resource "$SERVER_URL"
fi

say "Opening browser authorization..."
"$CODEX_BIN" mcp login "$SERVER_NAME" --scopes "$SCOPES"

say "Verifying saved configuration..."
"$CODEX_BIN" mcp get "$SERVER_NAME" --json
say "Barvinca MCP setup is complete. Restart Codex before starting a new task."
