#!/bin/bash
# =========================================================
# SETUP SYSTEMD SERVICES - IDS System
# =========================================================
# Installa e configura i servizi systemd per:
# - ids-ml-backend: Python FastAPI ML backend
# - ids-syslog-parser: Python syslog parser

set -e

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

IDS_DIR="/opt/ids"
SYSTEMD_DIR="${IDS_DIR}/deployment/systemd"

echo -e "${BLUE}🔧 Setup Systemd Services per IDS${NC}\n"

# Check se script è eseguito da root
if [ "$EUID" -ne 0 ]; then 
   echo -e "${RED}❌ Questo script deve essere eseguito come root (usa sudo)${NC}"
   exit 1
fi

# Verifica virtual environment Python
if [ ! -d "${IDS_DIR}/python_ml/venv" ]; then
    echo -e "${YELLOW}⚠️  Virtual environment Python non trovato${NC}"
    echo -e "${BLUE}📦 Eseguo installazione dipendenze...${NC}\n"
    "${IDS_DIR}/deployment/install_python_deps.sh"
    echo ""
fi

# Crea directory models per ML con permessi corretti
echo -e "${BLUE}📁 Creazione directory models...${NC}"
mkdir -p "${IDS_DIR}/python_ml/models"
chown -R ids:ids "${IDS_DIR}/python_ml/models"
chmod 755 "${IDS_DIR}/python_ml/models"
echo -e "${GREEN}✅ Directory models configurata${NC}"

# Verifica esistenza file .env
if [ ! -f "${IDS_DIR}/.env" ]; then
    echo -e "${RED}❌ File .env non trovato in ${IDS_DIR}/.env${NC}"
    exit 1
fi

# Genera API Key se non esiste
if ! grep -q "^IDS_API_KEY=" "${IDS_DIR}/.env"; then
    echo -e "${YELLOW}🔑 Generazione IDS_API_KEY...${NC}"
    API_KEY=$(openssl rand -hex 32)
    echo "IDS_API_KEY=${API_KEY}" >> "${IDS_DIR}/.env"
    echo -e "${GREEN}✅ IDS_API_KEY generata e salvata in .env${NC}"
fi

# Copia systemd units
echo -e "${BLUE}📋 Installazione systemd units...${NC}"
cp "${SYSTEMD_DIR}/ids-ml-backend.service" /etc/systemd/system/
cp "${SYSTEMD_DIR}/ids-syslog-parser.service" /etc/systemd/system/

# Reload systemd
echo -e "${BLUE}♻️  Reload systemd daemon...${NC}"
systemctl daemon-reload

# Stop servizi systemd esistenti (se presenti)
echo -e "${YELLOW}⏸️  Fermando servizi systemd esistenti...${NC}"
systemctl stop ids-ml-backend.service 2>/dev/null || true
systemctl stop ids-syslog-parser.service 2>/dev/null || true
sleep 1

# Kill TUTTI i processi Python manuali dell'utente ids
echo -e "${YELLOW}🧹 Pulizia processi Python manuali...${NC}"
pkill -9 -u ids -f "python.*main.py" 2>/dev/null || true
pkill -9 -u ids -f "python.*syslog_parser.py" 2>/dev/null || true
sleep 2

# Verifica che porta 8000 sia libera
if lsof -Pi :8000 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo -e "${RED}⚠️  Porta 8000 ancora occupata, killing processo...${NC}"
    lsof -ti:8000 | xargs kill -9 2>/dev/null || true
    sleep 1
fi

echo -e "${GREEN}✅ Pulizia completata${NC}"

# Enable e start services
echo -e "${BLUE}🚀 Attivazione servizi...${NC}"

# ML Backend
systemctl enable ids-ml-backend.service
systemctl start ids-ml-backend.service
echo -e "${GREEN}✅ ids-ml-backend.service attivato${NC}"

# Syslog Parser
systemctl enable ids-syslog-parser.service
systemctl start ids-syslog-parser.service
echo -e "${GREEN}✅ ids-syslog-parser.service attivato${NC}"

# Verifica status
sleep 2
echo -e "\n${BLUE}📊 Status Servizi:${NC}"
systemctl status ids-ml-backend.service --no-pager | head -10
echo ""
systemctl status ids-syslog-parser.service --no-pager | head -10

echo -e "\n${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ SYSTEMD SERVICES CONFIGURATI              ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"

echo -e "\n${BLUE}📚 COMANDI UTILI:${NC}"
echo -e "   ${YELLOW}systemctl status ids-ml-backend${NC}       - Status ML Backend"
echo -e "   ${YELLOW}systemctl status ids-syslog-parser${NC}    - Status Syslog Parser"
echo -e "   ${YELLOW}systemctl restart ids-ml-backend${NC}      - Restart ML Backend"
echo -e "   ${YELLOW}systemctl restart ids-syslog-parser${NC}   - Restart Syslog Parser"
echo -e "   ${YELLOW}journalctl -u ids-ml-backend -f${NC}       - Log ML Backend"
echo -e "   ${YELLOW}journalctl -u ids-syslog-parser -f${NC}    - Log Syslog Parser"
echo ""
