#!/usr/bin/env bash
# Cursor MCP: @yclenove/mysql-mcp-server on native Linux (Node 20+).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${PROJECT}"

if ! command -v node >/dev/null 2>&1; then
  echo "ERROR: Node.js not found. Install Node 20+ (nvm/fnm/apt)." >&2
  exit 1
fi

NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]")"
if [ "${NODE_MAJOR}" -lt 20 ] 2>/dev/null; then
  echo "ERROR: Node $(node -v) is too old; mysql-mcp-server needs Node 20+." >&2
  exit 1
fi

# Package reads MYSQL_* from process env; project .env is synced via sync_mysql_mcp_env.py
if [ -f .env ]; then
  set -a
  # shellcheck disable=SC1091
  while IFS= read -r line || [ -n "${line}" ]; do
    line="${line%$'\r'}"
    case "${line}" in
      MYSQL_*=*)
        key="${line%%=*}"
        val="${line#*=}"
        export "${key}=${val}"
        ;;
    esac
  done < .env
  set +a
fi

# Optional SOCKS/HTTP proxy for npx (see scripts/npm-proxy.env.example)
if [ -f "${SCRIPT_DIR}/npm-proxy.env" ]; then
  set -a
  # shellcheck disable=SC1091
  source "${SCRIPT_DIR}/npm-proxy.env"
  set +a
fi

MCP_BIN="${PROJECT}/node_modules/.bin/mysql-mcp-server"
if [ -x "${MCP_BIN}" ]; then
  exec "${MCP_BIN}"
fi

# npm/npx do not accept socks5:// in HTTP_PROXY (FETCH_ERROR). Use proxychains for npx fallback.
if command -v proxychains4 >/dev/null 2>&1 && [[ "${ALL_PROXY:-}${HTTP_PROXY:-}" == *socks5://* ]]; then
  exec proxychains4 -q npx -y @yclenove/mysql-mcp-server
fi
exec npx -y @yclenove/mysql-mcp-server
