#!/bin/bash
# =========================================================
# IDS - Cleanup Detections Runner
# =========================================================
# Esegue cleanup automatico delle detections secondo regole:
# - Cancella detections non anomale dopo 48h
# - Sblocca IP bloccati se non più anomali dopo 2h
#
# Uso: ./run_cleanup.sh
# =========================================================

set -e

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

# Carica variabili ambiente
if [ -f "$PROJECT_ROOT/.env" ]; then
    set -a
    source "$PROJECT_ROOT/.env"
    set +a
else
    echo "❌ File .env non trovato in $PROJECT_ROOT"
    exit 1
fi

# Log
LOG_FILE="/var/log/ids/cleanup.log"
mkdir -p /var/log/ids

echo "=========================================" >> "$LOG_FILE"
echo "[$(date)] Cleanup automatico avviato" >> "$LOG_FILE"
echo "=========================================" >> "$LOG_FILE"

# Esegui cleanup
cd "$PROJECT_ROOT"
python3 python_ml/cleanup_detections.py >> "$LOG_FILE" 2>&1

EXIT_CODE=$?

if [ $EXIT_CODE -eq 0 ]; then
    echo "[$(date)] Cleanup completato con successo" >> "$LOG_FILE"
else
    echo "[$(date)] Cleanup fallito (exit code: $EXIT_CODE)" >> "$LOG_FILE"
fi

echo "" >> "$LOG_FILE"
exit $EXIT_CODE
