#!/usr/bin/env bash
# Stop local dev stack. Usage: ./scripts/dev-stop.sh
set -uo pipefail
cd "$(dirname "$0")/.."

stopped=0
for port in 3999 4001; do
  pids=$(lsof -ti :$port 2>/dev/null || true)
  if [ -n "$pids" ]; then
    echo "stopping :$port (pid: $pids)"
    kill $pids 2>/dev/null || true
    stopped=1
  fi
done

# also kill recorded pids
for f in tmp/server.pid tmp/fe.pid; do
  if [ -f "$f" ]; then
    pid=$(cat "$f")
    kill "$pid" 2>/dev/null || true
    rm -f "$f"
  fi
done

# node --watch spawns children — sweep by port pattern
pids=$(pgrep -f "node --watch index.js|react-scripts start" 2>/dev/null || true)
if [ -n "$pids" ]; then
  echo "sweeping node dev procs: $pids"
  kill $pids 2>/dev/null || true
fi

if [ "$stopped" = "0" ]; then
  echo "nothing running."
fi
echo "stopped."
