#!/usr/bin/env bash
# Install Cursor CLI and gitea-mcp only when missing (runner cache friendly).
set -euo pipefail

ensure_path() {
  if [ -d "$HOME/.local/bin" ] && [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    echo "$HOME/.local/bin" >> "${GITHUB_PATH:?GITHUB_PATH is not set}"
  fi
}

install_cursor_cli() {
  if command -v agent >/dev/null 2>&1; then
    echo "Cursor CLI already installed at $(command -v agent)"
    return 0
  fi

  echo "Installing Cursor CLI..."
  curl -fsSL https://cursor.com/install | bash
  ensure_path
}

install_gitea_mcp() {
  local mcp_dir="/tmp/gitea-mcp"
  local mcp_bin="${mcp_dir}/gitea-mcp"
  local mcp_version="v1.3.0"
  local arch asset arch_name

  if [ -x "$mcp_bin" ]; then
    echo "gitea-mcp already installed at $mcp_bin"
    return 0
  fi

  arch=$(uname -m)
  case "$arch" in
    x86_64) asset="Linux_x86_64" ;;
    aarch64|arm64) asset="Linux_arm64" ;;
    *)
      echo "Unsupported architecture for gitea-mcp: $arch"
      exit 1
      ;;
  esac

  mkdir -p "$mcp_dir"
  cd "$mcp_dir"

  arch_name="gitea-mcp_${asset}.tar.gz"
  url="https://gitea.com/gitea/gitea-mcp/releases/download/${mcp_version}/${arch_name}"

  echo "Downloading gitea-mcp ${mcp_version} (${asset})..."
  curl -fsSL "$url" -o gitea-mcp.tar.gz
  tar -xzf gitea-mcp.tar.gz
  chmod +x gitea-mcp
  rm -f gitea-mcp.tar.gz

  echo "gitea-mcp ready at $mcp_bin"
}

install_cursor_cli
install_gitea_mcp
