#!/bin/bash
# =========================================================
# CHECK BACKEND - Verifica e riavvia backend Python se necessario
# =========================================================

PROCESS_NAME="python3.11 python_ml/main.py"
PID_FILE="/var/log/ids/backend.pid"
LOG_FILE="/var/log/ids/backend.log"
WORK_DIR="/opt/ids"

mkdir -p /var/log/ids

# Check if backend is running
if pgrep -f "$PROCESS_NAME" > /dev/null; then
    # Backend running, update PID
    pgrep -f "$PROCESS_NAME" > "$PID_FILE"
    exit 0
else
    echo "[$(date)] Backend Python NON attivo, riavvio..." >> "$LOG_FILE"
    
    # Kill any orphaned Python processes
    pkill -f "python_ml/main.py" 2>/dev/null
    
    # Wait a moment
    sleep 2
    
    # Start backend
    cd "$WORK_DIR/python_ml"
    nohup /usr/bin/python3.11 main.py >> "$LOG_FILE" 2>&1 &
    NEW_PID=$!
    echo $NEW_PID > "$PID_FILE"
    
    echo "[$(date)] Backend riavviato con PID: $NEW_PID" >> "$LOG_FILE"
fi
