#!/bin/sh
set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PID_FILE="$SCRIPT_DIR/server.pid"
PORT="${PORT:-8000}"

PID=""
if [ -f "$PID_FILE" ]; then
  PID=$(cat "$PID_FILE")
fi

if [ -z "$PID" ] || ! kill -0 "$PID" 2>/dev/null; then
  PID=$(lsof -tiTCP:"$PORT" -sTCP:LISTEN 2>/dev/null || true)
fi

if [ -z "$PID" ]; then
  rm -f "$PID_FILE"
  echo "No server is running on port $PORT"
  exit 0
fi

kill "$PID"

COUNT=0
while kill -0 "$PID" 2>/dev/null; do
  COUNT=$((COUNT + 1))
  if [ "$COUNT" -ge 20 ]; then
    echo "Server did not stop after 10 seconds. Try: kill -9 $PID"
    exit 1
  fi
  sleep 0.5
done

rm -f "$PID_FILE"
echo "Server stopped. PID was $PID"
