#!/bin/bash
# SamCloud Dashboard Management Script
# Safely manages the dashboard without affecting OrbStack containers

DASHBOARD_DIR="/Volumes/SamMgmt/Containers/SamCloud-Dashboard"
DASHBOARD_SCRIPT="advanced_homelab_dashboard.py"
DASHBOARD_PORT=5001
DASHBOARD_LOG="$DASHBOARD_DIR/dashboard.log"
DASHBOARD_PID_FILE="$DASHBOARD_DIR/dashboard.pid"

cd "$DASHBOARD_DIR" || { echo "Error: Cannot access dashboard directory"; exit 1; }

# Activate virtual environment
if [ -d "dashboard_env" ]; then
    source dashboard_env/bin/activate
elif [ -d "venv" ]; then
    source venv/bin/activate
fi

# Function to check if dashboard is running
is_dashboard_running() {
    if [ -f "$DASHBOARD_PID_FILE" ]; then
        PID=$(cat "$DASHBOARD_PID_FILE")
        if ps -p "$PID" > /dev/null; then
            return 0  # Running
        fi
    fi
    return 1  # Not running
}

# Gently stop the dashboard without affecting other services
stop_dashboard() {
    echo "Stopping SamCloud Dashboard..."
    
    # First try using PID file
    if [ -f "$DASHBOARD_PID_FILE" ]; then
        PID=$(cat "$DASHBOARD_PID_FILE")
        if ps -p "$PID" > /dev/null; then
            echo "Sending SIGTERM to process $PID"
            kill "$PID" 2>/dev/null
            sleep 2
            if ps -p "$PID" > /dev/null; then
                echo "Dashboard didn't stop gracefully, sending SIGKILL"
                kill -9 "$PID" 2>/dev/null
            fi
        else
            echo "Dashboard process not running, but PID file exists"
        fi
        rm -f "$DASHBOARD_PID_FILE"
    fi
    
    # Check for Python processes specifically running the dashboard script
    PIDS=$(ps aux | grep "$DASHBOARD_SCRIPT" | grep -v grep | awk '{print $2}')
    if [ -n "$PIDS" ]; then
        echo "Found dashboard processes: $PIDS"
        for P in $PIDS; do
            echo "Stopping process $P"
            kill "$P" 2>/dev/null
            sleep 1
        done
    fi
    
    # Check for any process using the dashboard port
    PORT_PID=$(lsof -ti:$DASHBOARD_PORT)
    if [ -n "$PORT_PID" ]; then
        echo "Found process using port $DASHBOARD_PORT: $PORT_PID"
        echo "Stopping process $PORT_PID"
        kill "$PORT_PID" 2>/dev/null
        sleep 2
        
        # If it's still running, force kill
        if lsof -ti:$DASHBOARD_PORT > /dev/null; then
            echo "Process didn't stop gracefully, force killing"
            kill -9 $(lsof -ti:$DASHBOARD_PORT) 2>/dev/null
        fi
    fi
    
    echo "Dashboard stopped"
}

# Start the dashboard
start_dashboard() {
    echo "Starting SamCloud Dashboard on port $DASHBOARD_PORT..."
    python3 "$DASHBOARD_SCRIPT" > "$DASHBOARD_LOG" 2>&1 &
    PID=$!
    echo $PID > "$DASHBOARD_PID_FILE"
    echo "Dashboard started with PID $PID"
    echo "Log file: $DASHBOARD_LOG"
    sleep 2
    if ps -p "$PID" > /dev/null; then
        echo "Dashboard is running successfully"
    else
        echo "Dashboard failed to start. Check log file: $DASHBOARD_LOG"
        cat "$DASHBOARD_LOG"
    fi
}

# Restart the dashboard
restart_dashboard() {
    stop_dashboard
    sleep 2
    start_dashboard
}

# Check dashboard status
status_dashboard() {
    if is_dashboard_running; then
        PID=$(cat "$DASHBOARD_PID_FILE")
        echo "Dashboard is running with PID $PID"
        echo "Dashboard URL: http://localhost:$DASHBOARD_PORT"
        echo "External URL: https://home.samcloud.ca"
    else
        echo "Dashboard is not running"
    fi
}

# Command handling
case "$1" in
    start)
        if is_dashboard_running; then
            echo "Dashboard is already running"
            status_dashboard
        else
            start_dashboard
        fi
        ;;
    stop)
        stop_dashboard
        ;;
    restart)
        restart_dashboard
        ;;
    status)
        status_dashboard
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        exit 1
        ;;
esac

exit 0
