#!/usr/bin/env bash
# Restart the WLED Screen Controller server (Linux/macOS)
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

# Stop any running instance
PIDS=$(pgrep -f 'wled_controller\.main' 2>/dev/null || true)
if [ -n "$PIDS" ]; then
    echo "Stopping server (PID $PIDS)..."
    pkill -f 'wled_controller\.main' 2>/dev/null || true
    sleep 2
fi

# Start server detached
echo "Starting server..."
cd "$SCRIPT_DIR"
nohup python -m wled_controller.main > /dev/null 2>&1 &
sleep 3

# Verify it's running
NEW_PID=$(pgrep -f 'wled_controller\.main' 2>/dev/null || true)
if [ -n "$NEW_PID" ]; then
    echo "Server started (PID $NEW_PID)"
else
    echo "WARNING: Server does not appear to be running!"
fi
