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

PORT="${PORT:-8550}"
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$ROOT_DIR"

echo "Killing atlas2-mcp listeners on port ${PORT} (stray uvicorn processes)..."

if command -v ss >/dev/null 2>&1; then
  # Get PIDs listening on the TCP port.
  PIDS=$(ss -ltnp 2>/dev/null | awk -v port=":${PORT}" '$4 ~ port {print $NF}' | sed -E 's/users:\(\("([^,]+)".*pid=([0-9]+).*/\2/' | tr -d '"' || true)
elif command -v lsof >/dev/null 2>&1; then
  PIDS=$(lsof -t -iTCP:"${PORT}" -sTCP:LISTEN 2>/dev/null || true)
else
  echo "Neither 'ss' nor 'lsof' found; cannot auto-kill by port." >&2
  exit 1
fi

if [[ -z "${PIDS:-}" ]]; then
  echo "No listeners found on port ${PORT}."
  exit 0
fi

# Kill unique PIDs.
echo "Found PIDs: ${PIDS}"
PIDS_UNIQ=$(echo "$PIDS" | tr ' ' '\n' | awk 'NF' | sort -u)

for pid in $PIDS_UNIQ; do
  if [[ "$pid" =~ ^[0-9]+$ ]]; then
    echo "Killing PID ${pid}..."
    kill -9 "$pid" 2>/dev/null || true
  fi
done

echo "Done."

