#!/bin/bash
# =========================================================
# IDS - Setup Cleanup Timer
# =========================================================
# Installa e avvia il timer systemd per cleanup automatico
#
# Uso: sudo ./deployment/setup_cleanup_timer.sh
# =========================================================

set -e

if [ "$EUID" -ne 0 ]; then 
    echo "❌ Questo script deve essere eseguito come root (sudo)"
    exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

echo "🔧 Setup IDS Cleanup Timer..."
echo ""

# 1. Installa dipendenze Python
echo "[1/7] Installazione dipendenze Python..."
pip3 install -q psycopg2-binary python-dotenv || {
    echo "⚠️  Installazione pip fallita, provo con requirements.txt..."
    pip3 install -q -r "$SCRIPT_DIR/../python_ml/requirements.txt" || {
        echo "❌ Errore installazione dipendenze!"
        echo "💡 Esegui manualmente: sudo pip3 install psycopg2-binary python-dotenv"
        exit 1
    }
}

# 2. Crea directory log
echo "[2/7] Creazione directory log..."
mkdir -p /var/log/ids
chmod 755 /var/log/ids

# 3. Rendi eseguibili gli script
echo "[3/7] Permessi esecuzione script..."
chmod +x "$SCRIPT_DIR/run_cleanup.sh"
chmod +x "$SCRIPT_DIR/../python_ml/cleanup_detections.py"

# 4. Copia service file
echo "[4/7] Installazione service file..."
cp "$SCRIPT_DIR/systemd/ids-cleanup.service" /etc/systemd/system/
cp "$SCRIPT_DIR/systemd/ids-cleanup.timer" /etc/systemd/system/

# 5. Reload systemd
echo "[5/7] Reload systemd daemon..."
systemctl daemon-reload

# 6. Abilita timer
echo "[6/7] Abilitazione timer..."
systemctl enable ids-cleanup.timer

# 7. Avvia timer
echo "[7/7] Avvio timer..."
systemctl start ids-cleanup.timer

echo ""
echo "✅ Cleanup timer installato e avviato con successo!"
echo ""
echo "📊 Status:"
systemctl status ids-cleanup.timer --no-pager -l
echo ""
echo "📅 Prossima esecuzione:"
systemctl list-timers ids-cleanup.timer --no-pager
echo ""
echo "💡 Comandi utili:"
echo "  - Test manuale:        sudo ./deployment/run_cleanup.sh"
echo "  - Esegui ora:          sudo systemctl start ids-cleanup.service"
echo "  - Stato timer:         sudo systemctl status ids-cleanup.timer"
echo "  - Log cleanup:         tail -f /var/log/ids/cleanup.log"
echo "  - Disabilita timer:    sudo systemctl stop ids-cleanup.timer && sudo systemctl disable ids-cleanup.timer"
echo ""
