#!/usr/bin/bash
#
# camcomDemoStop - Stop the CamCom demo (simulated camera) environment
#
# Stops all processes started by camcomDemoStart
#

PID_FILE="/tmp/camcom_demo.pids"

stop_process() {
    local name="$1"
    local pid="$2"
    local term_pid="$3"
    
    if [[ -z "$pid" ]] || [[ "$pid" == "0" ]]; then
        return
    fi
    
    if kill -0 "$pid" 2>/dev/null; then
        echo "Stopping $name (PID $pid)..."
        kill "$pid" 2>/dev/null
        # Wait up to 3 seconds for graceful shutdown
        for i in {1..6}; do
            if ! kill -0 "$pid" 2>/dev/null; then
                echo "  $name stopped"
                break
            fi
            sleep 0.5
        done
        # Force kill if still running
        if kill -0 "$pid" 2>/dev/null; then
            echo "  $name not responding, force killing..."
            kill -9 "$pid" 2>/dev/null || true
        fi
    else
        echo "$name (PID $pid) not running"
    fi
    
    # Also kill the terminal process if tracked separately
    if [[ -n "$term_pid" ]] && [[ "$term_pid" != "0" ]]; then
        if kill -0 "$term_pid" 2>/dev/null; then
            echo "  Closing terminal (PID $term_pid)..."
            kill "$term_pid" 2>/dev/null || true
        fi
    fi
}

if [[ ! -f "$PID_FILE" ]]; then
    echo "No PID file found ($PID_FILE)"
    echo "Attempting to find processes by name..."
    
    # Fallback: find and kill by process name (sim config)
    pkill -f "camcomGui.*example_sim" 2>/dev/null && echo "Stopped camcomGui" || true
    pkill -f "camcomServer.*example_sim" 2>/dev/null && echo "Stopped camcomServer" || true
    
    exit 0
fi

# Load PIDs
source "$PID_FILE"

echo "Stopping CamCom Sim Environment..."

# Stop in reverse order: GUI -> Server
stop_process "GUI" "${GUI_PID:-}" ""
stop_process "Server" "${SRV_PID:-}" "${SRV_TERM_PID:-}"

# Cleanup PID file
rm -f "$PID_FILE"

echo "Environment stopped."
