#!/bin/bash
# =========================================================
# RESTART ALL - Riavvio completo sistema IDS
# Usa systemctl per ML Backend, processo diretto per frontend
# =========================================================

LOG_FILE="/var/log/ids/cron.log"

echo "$(date): === RESTART SETTIMANALE SISTEMA IDS ===" >> "$LOG_FILE"

# Stop ML Backend via systemctl
echo "$(date): Arresto servizi..." >> "$LOG_FILE"
systemctl stop ids-ml-backend 2>/dev/null

# Stop frontend processes
pkill -f "vite" 2>/dev/null
pkill -f "npm run dev" 2>/dev/null

sleep 5

# Clean temp files
echo "$(date): Pulizia file temporanei..." >> "$LOG_FILE"
rm -f /var/log/ids/*.pid
find /tmp -name "ids_*" -mtime +7 -delete 2>/dev/null

# Restart ML Backend via systemctl
echo "$(date): Riavvio servizi..." >> "$LOG_FILE"
systemctl start ids-ml-backend
sleep 3

# Restart frontend via check script
/opt/ids/deployment/check_frontend.sh >> "$LOG_FILE" 2>&1

# Verify ML Backend
if systemctl is-active --quiet ids-ml-backend; then
    echo "$(date): ML Backend avviato con successo" >> "$LOG_FILE"
else
    echo "$(date): ERRORE: ML Backend non si è avviato" >> "$LOG_FILE"
fi

# Verify Frontend
if pgrep -f "vite" > /dev/null; then
    echo "$(date): Frontend avviato con successo" >> "$LOG_FILE"
else
    echo "$(date): ERRORE: Frontend non si è avviato" >> "$LOG_FILE"
fi

echo "$(date): Restart completato!" >> "$LOG_FILE"
