#!/bin/bash
#
# Kill All Development Servers Script
# Ensures no development servers (react-scripts, webpack-dev-server) are running
# This should be run before starting production services
#

set -e

echo "=========================================="
echo "Killing all development servers..."
echo "=========================================="

# Kill react-scripts (development server)
echo "Checking for react-scripts processes..."
REACT_PIDS=$(pgrep -f "react-scripts" || true)
if [ -n "$REACT_PIDS" ]; then
    echo "Found react-scripts processes: $REACT_PIDS"
    pkill -9 -f "react-scripts" || true
    echo "✓ Killed react-scripts"
else
    echo "✓ No react-scripts processes found"
fi

# Kill webpack-dev-server
echo "Checking for webpack-dev-server processes..."
WEBPACK_PIDS=$(pgrep -f "webpack-dev-server" || true)
if [ -n "$WEBPACK_PIDS" ]; then
    echo "Found webpack-dev-server processes: $WEBPACK_PIDS"
    pkill -9 -f "webpack-dev-server" || true
    echo "✓ Killed webpack-dev-server"
else
    echo "✓ No webpack-dev-server processes found"
fi

# Kill any Python dev servers (app.py running directly, NOT gunicorn)
echo "Checking for Python dev servers..."
# Only kill python processes running app.py directly, NOT gunicorn workers
for pid in $(pgrep -f "python.*app\.py" || true); do
    CMD=$(ps -p $pid -o args= 2>/dev/null || true)
    # Skip if it's a gunicorn worker
    if echo "$CMD" | grep -q "gunicorn"; then
        echo "Skipping gunicorn process: $pid"
        continue
    fi
    # Kill if it's a direct python app.py process
    if echo "$CMD" | grep -q "python.*app\.py"; then
        echo "Killing Python dev server: $pid ($CMD)"
        kill -9 $pid 2>/dev/null || true
    fi
done
echo "✓ Python dev server check complete"

# Wait for ports to be released
echo "Waiting for ports to be released..."
sleep 1

# Verify port 5100 is free (except for production serve)
PORT_5100=$(lsof -i :5100 2>/dev/null | grep -v "serve" || true)
if [ -n "$PORT_5100" ]; then
    echo "⚠ Warning: Port 5100 in use by non-serve process"
    echo "$PORT_5100"
    # Only kill non-serve processes on port 5100
    lsof -i :5100 2>/dev/null | grep -v -E "serve|COMMAND" | awk '{print $2}' | xargs -r kill -9 || true
    sleep 1
else
    echo "✓ Port 5100 is free or only used by serve"
fi

echo "=========================================="
echo "✓ All development servers killed"
echo "✓ Ports verified (production services preserved)"
echo "=========================================="

exit 0
