#!/usr/bin/env bash
# Clone/build local MCP servers into ./mcp-servers (local-clone policy).

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
MCP_DIR="${REPO_ROOT}/mcp-servers"

usage() {
  cat <<'EOF'
usage:
  ./scripts/setup-mcp-servers.sh gitea

notes:
  - clones into ./mcp-servers/<name>
  - builds artifacts needed to run the MCP server locally
EOF
}

need_cmd() {
  local cmd="$1"
  if ! command -v "${cmd}" >/dev/null 2>&1; then
    echo "error: missing '${cmd}' on PATH" >&2
    return 1
  fi
}

need_go_min() {
  local want_major="$1"
  local want_minor="$2"

  local v
  v="$(go version 2>/dev/null || true)"
  # Example: "go version go1.26.0 linux/amd64"
  local ver
  ver="$(echo "${v}" | awk '{print $3}' | sed 's/^go//')"
  local major minor
  major="$(echo "${ver}" | cut -d. -f1)"
  minor="$(echo "${ver}" | cut -d. -f2)"

  if [[ -z "${major}" || -z "${minor}" ]]; then
    echo "error: could not parse Go version from: ${v}" >&2
    return 1
  fi

  # Compare major/minor only (sufficient for our use).
  if (( major < want_major )) || { (( major == want_major )) && (( minor < want_minor )); }; then
    echo "error: Go ${want_major}.${want_minor}+ required; found ${ver}" >&2
    return 1
  fi
}

setup_gitea() {
  need_cmd git

  if ! command -v go >/dev/null 2>&1; then
    cat <<'EOF' >&2
error: Go toolchain not found (required to build gitea-mcp).

install one of:
  - Debian/Ubuntu: sudo apt-get update && sudo apt-get install -y golang
  - Or install Go from https://go.dev/dl/

then rerun:
  ./scripts/setup-mcp-servers.sh gitea
EOF
    exit 2
  fi

  if ! need_go_min 1 26; then
    cat <<'EOF' >&2

gitea-mcp currently requires a newer Go toolchain than Debian stable typically ships.
If you already installed a newer Go under /usr/local (example: /usr/local/go1.26/bin/go),
rerun with PATH overridden, e.g.:

  PATH="/usr/local/go1.26/bin:$PATH" ./scripts/setup-mcp-servers.sh gitea
EOF
    exit 2
  fi

  mkdir -p "${MCP_DIR}"

  if [[ ! -d "${MCP_DIR}/gitea-mcp/.git" ]]; then
    git clone https://gitea.com/gitea/gitea-mcp.git "${MCP_DIR}/gitea-mcp"
  else
    echo "info: gitea-mcp already cloned, skipping clone"
  fi

  (cd "${MCP_DIR}/gitea-mcp" && go build -o gitea-mcp .)

  echo "done: built ${MCP_DIR}/gitea-mcp/gitea-mcp"
}

main() {
  if [[ "${#}" -ne 1 ]]; then
    usage
    exit 1
  fi

  case "$1" in
    gitea) setup_gitea ;;
    -h|--help|help) usage ;;
    *)
      echo "error: unknown target '$1'" >&2
      usage
      exit 1
      ;;
  esac
}

main "$@"

