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

# Stops the Wikipedia3D FastAPI server.

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="$ROOT_DIR/.uvicorn.pid"

if [[ -f "$PID_FILE" ]]; then
  PID="$(cat "$PID_FILE")"
  if kill -0 "$PID" 2>/dev/null; then
    kill "$PID"
    echo "Stopped server (pid $PID)."
  else
    echo "PID file found but process not running."
  fi
  rm -f "$PID_FILE"
  exit 0
fi

# Fallback if pid file is missing.
if pgrep -f "uvicorn server.app:app" >/dev/null; then
  pkill -f "uvicorn server.app:app"
  echo "Stopped server via pkill."
else
  echo "Server not running."
fi
