#!/bin/bash
# =========================================================
# CHECK FRONTEND - Verifica e riavvia frontend Node.js se necessario
# =========================================================

PROCESS_NAME="npm run dev"
PID_FILE="/var/log/ids/frontend.pid"
LOG_FILE="/var/log/ids/frontend.log"
WORK_DIR="/opt/ids"

mkdir -p /var/log/ids

# Check if frontend is running
if pgrep -f "vite" > /dev/null; then
    # Frontend running, update PID
    pgrep -f "vite" > "$PID_FILE"
    exit 0
else
    echo "[$(date)] Frontend Node NON attivo, riavvio..." >> "$LOG_FILE"
    
    # Kill any orphaned Node processes
    pkill -f "vite" 2>/dev/null
    pkill -f "npm run dev" 2>/dev/null
    
    # Wait a moment
    sleep 2
    
    # Start frontend with environment variables from .env
    cd "$WORK_DIR"
    if [ -f "$WORK_DIR/.env" ]; then
        # Load .env and start npm with those variables
        nohup env $(cat "$WORK_DIR/.env" | grep -v '^#' | xargs) npm run dev >> "$LOG_FILE" 2>&1 &
    else
        # Fallback: start without .env (will use system env vars)
        nohup npm run dev >> "$LOG_FILE" 2>&1 &
    fi
    NEW_PID=$!
    echo $NEW_PID > "$PID_FILE"
    
    echo "[$(date)] Frontend riavviato con PID: $NEW_PID" >> "$LOG_FILE"
fi
