#!/bin/bash
# =============================================================================
# IDS - Installazione Servizio List Fetcher
# =============================================================================
# Installa e configura il servizio systemd per il fetcher delle liste pubbliche
# Eseguire come ROOT: ./install_list_fetcher.sh
# =============================================================================

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}"
echo "╔═══════════════════════════════════════════════╗"
echo "║   📋 INSTALLAZIONE IDS LIST FETCHER           ║"
echo "╚═══════════════════════════════════════════════╝"
echo -e "${NC}"

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

# Verifica di essere root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}❌ Questo script deve essere eseguito come root${NC}"
    echo -e "${YELLOW}   Esegui: sudo ./install_list_fetcher.sh${NC}"
    exit 1
fi

# Verifica che i file sorgente esistano
SERVICE_SRC="$IDS_DIR/deployment/systemd/ids-list-fetcher.service"
TIMER_SRC="$IDS_DIR/deployment/systemd/ids-list-fetcher.timer"

if [ ! -f "$SERVICE_SRC" ]; then
    echo -e "${RED}❌ File service non trovato: $SERVICE_SRC${NC}"
    exit 1
fi

if [ ! -f "$TIMER_SRC" ]; then
    echo -e "${RED}❌ File timer non trovato: $TIMER_SRC${NC}"
    exit 1
fi

# Verifica che il virtual environment Python esista
VENV_PYTHON="$IDS_DIR/python_ml/venv/bin/python3"
if [ ! -f "$VENV_PYTHON" ]; then
    echo -e "${YELLOW}⚠️  Virtual environment non trovato, creazione...${NC}"
    cd "$IDS_DIR/python_ml"
    python3.11 -m venv venv
    ./venv/bin/pip install --upgrade pip
    ./venv/bin/pip install -r requirements.txt
    echo -e "${GREEN}✅ Virtual environment creato${NC}"
fi

# Verifica che run_fetcher.py esista
FETCHER_SCRIPT="$IDS_DIR/python_ml/list_fetcher/run_fetcher.py"
if [ ! -f "$FETCHER_SCRIPT" ]; then
    echo -e "${RED}❌ Script fetcher non trovato: $FETCHER_SCRIPT${NC}"
    exit 1
fi

# Copia file systemd
echo -e "${BLUE}📦 Installazione file systemd...${NC}"

cp "$SERVICE_SRC" "$SYSTEMD_DIR/ids-list-fetcher.service"
cp "$TIMER_SRC" "$SYSTEMD_DIR/ids-list-fetcher.timer"

echo -e "${GREEN}   ✅ ids-list-fetcher.service installato${NC}"
echo -e "${GREEN}   ✅ ids-list-fetcher.timer installato${NC}"

# Ricarica systemd
echo -e "${BLUE}🔄 Ricarica configurazione systemd...${NC}"
systemctl daemon-reload
echo -e "${GREEN}✅ Daemon ricaricato${NC}"

# Abilita e avvia timer
echo -e "${BLUE}⏱️  Abilitazione timer (ogni 10 minuti)...${NC}"
systemctl enable ids-list-fetcher.timer
systemctl start ids-list-fetcher.timer
echo -e "${GREEN}✅ Timer abilitato e avviato${NC}"

# Test esecuzione manuale
echo -e "${BLUE}🧪 Test esecuzione fetcher...${NC}"
if systemctl start ids-list-fetcher.service; then
    echo -e "${GREEN}✅ Fetcher eseguito con successo${NC}"
else
    echo -e "${YELLOW}⚠️  Prima esecuzione potrebbe fallire se liste non configurate${NC}"
fi

# Mostra stato
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ INSTALLAZIONE COMPLETATA                 ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}📋 COMANDI UTILI:${NC}"
echo -e "   • Stato timer:     ${YELLOW}systemctl status ids-list-fetcher.timer${NC}"
echo -e "   • Stato service:   ${YELLOW}systemctl status ids-list-fetcher.service${NC}"
echo -e "   • Esegui manuale:  ${YELLOW}systemctl start ids-list-fetcher.service${NC}"
echo -e "   • Visualizza logs: ${YELLOW}journalctl -u ids-list-fetcher -n 50${NC}"
echo -e "   • Timer attivi:    ${YELLOW}systemctl list-timers | grep ids${NC}"
echo ""
