#!/usr/bin/env bash
set -euo pipefail

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

PID_FILE="logs/server.pid"
LEGACY_PID_FILE="server.pid"
PORT="${MCP_PORT:-${PORT:-8550}}"

echo "[killserver] Checking for running atlas-mcp instances..."

for pidfile in "$PID_FILE" "$LEGACY_PID_FILE"; do
  if [[ -f "$pidfile" ]]; then
    PID="$(cat "$pidfile" 2>/dev/null || true)"
    if [[ -n "${PID:-}" ]] && kill -0 "$PID" 2>/dev/null; then
      echo "[killserver] Stopping PID from pidfile: $PID"
      kill "$PID" || true
      sleep 0.5
      if kill -0 "$PID" 2>/dev/null; then
        echo "[killserver] PID $PID still alive, sending SIGKILL"
        kill -9 "$PID" || true
      fi
    else
      echo "[killserver] Stale or empty pidfile, removing."
    fi
    rm -f "$pidfile"
  fi
done

STRAY_PIDS="$(ps -ef | grep -E 'uvicorn[[:space:]]+app\.main:app' | grep -v grep | awk '{print $2}' || true)"
if [[ -n "${STRAY_PIDS:-}" ]]; then
  echo "[killserver] Killing stray uvicorn PIDs: $STRAY_PIDS"
  for p in $STRAY_PIDS; do
    kill "$p" || true
  done
  sleep 0.5
  for p in $STRAY_PIDS; do
    if kill -0 "$p" 2>/dev/null; then
      kill -9 "$p" || true
    fi
  done
fi

if command -v lsof >/dev/null 2>&1; then
  PORT_PIDS="$(lsof -ti tcp:"$PORT" || true)"
  if [[ -n "${PORT_PIDS:-}" ]]; then
    echo "[killserver] Port $PORT still in use by: $PORT_PIDS"
    for p in $PORT_PIDS; do
      kill "$p" || true
    done
    sleep 0.5
    for p in $PORT_PIDS; do
      if kill -0 "$p" 2>/dev/null; then
        kill -9 "$p" || true
      fi
    done
  fi
fi

echo "[killserver] Done."
