#!/bin/bash
#
# Setup ML Training Systemd Timer
# Configura training automatico settimanale del modello ML hybrid
#

set -e

echo "================================================================"
echo "  SETUP ML TRAINING TIMER - Training Automatico Settimanale"
echo "================================================================"
echo ""

# Verifica root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ ERRORE: Questo script deve essere eseguito come root"
    echo "   Usa: sudo $0"
    exit 1
fi

IDS_ROOT="/opt/ids"
SYSTEMD_DIR="/etc/systemd/system"

# Verifica directory IDS
if [ ! -d "$IDS_ROOT" ]; then
    echo "❌ ERRORE: Directory IDS non trovata: $IDS_ROOT"
    exit 1
fi

echo "📁 Directory IDS: $IDS_ROOT"
echo ""

# 1. Copia systemd files
echo "📋 Step 1: Installazione systemd units..."

cp "$IDS_ROOT/deployment/systemd/ids-ml-training.service" "$SYSTEMD_DIR/"
cp "$IDS_ROOT/deployment/systemd/ids-ml-training.timer" "$SYSTEMD_DIR/"

echo "   ✅ Service copiato: $SYSTEMD_DIR/ids-ml-training.service"
echo "   ✅ Timer copiato: $SYSTEMD_DIR/ids-ml-training.timer"
echo ""

# 2. Rendi eseguibile script
echo "🔧 Step 2: Permessi script..."
chmod +x "$IDS_ROOT/deployment/run_ml_training.sh"
echo "   ✅ Script eseguibile: $IDS_ROOT/deployment/run_ml_training.sh"
echo ""

# 3. Reload systemd
echo "🔄 Step 3: Reload systemd daemon..."
systemctl daemon-reload
echo "   ✅ Daemon reloaded"
echo ""

# 4. Enable e start timer
echo "🚀 Step 4: Attivazione timer..."
systemctl enable ids-ml-training.timer
systemctl start ids-ml-training.timer
echo "   ✅ Timer attivato e avviato"
echo ""

# 5. Verifica status
echo "📊 Step 5: Verifica configurazione..."
echo ""
echo "Timer status:"
systemctl status ids-ml-training.timer --no-pager
echo ""
echo "Prossima esecuzione:"
systemctl list-timers ids-ml-training.timer --no-pager
echo ""

echo "================================================================"
echo "✅ SETUP COMPLETATO!"
echo "================================================================"
echo ""
echo "📅 Schedule: Ogni Lunedì alle 03:00 AM"
echo "📁 Log: /var/log/ids/ml-training.log"
echo ""
echo "🔍 COMANDI UTILI:"
echo ""
echo "  # Verifica timer attivo"
echo "  systemctl status ids-ml-training.timer"
echo ""
echo "  # Vedi prossima esecuzione"
echo "  systemctl list-timers ids-ml-training.timer"
echo ""
echo "  # Esegui training manualmente ORA"
echo "  sudo systemctl start ids-ml-training.service"
echo ""
echo "  # Vedi log training"
echo "  journalctl -u ids-ml-training.service -f"
echo "  tail -f /var/log/ids/ml-training.log"
echo ""
echo "  # Disabilita training automatico"
echo "  sudo systemctl stop ids-ml-training.timer"
echo "  sudo systemctl disable ids-ml-training.timer"
echo ""
echo "================================================================"
