#!/bin/bash
# =============================================================================
# SETUP RSYSLOG per IDS MikroTik
# =============================================================================
# Configura rsyslog per ricevere log UDP:514 e salvarli senza duplicati
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RSYSLOG_CONF="/etc/rsyslog.d/99-mikrotik.conf"
LOG_DIR="/var/log/mikrotik"

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

echo -e "${BLUE}🔧 Setup RSyslog per IDS MikroTik${NC}"
echo ""

# 1. Verifica rsyslog installato
if ! command -v rsyslogd &> /dev/null; then
    echo -e "${RED}❌ rsyslog non installato${NC}"
    echo -e "${YELLOW}   Installa: sudo dnf install rsyslog -y${NC}"
    exit 1
fi

echo -e "${BLUE}📋 Configurazione RSyslog...${NC}"

# 2. Rimuovi vecchie configurazioni conflittuali
echo -e "${YELLOW}   Rimuovo vecchie configurazioni...${NC}"
rm -f /etc/rsyslog.d/10-mikrotik.conf
rm -f /etc/rsyslog.d/mikrotik.conf

# 3. Copia nuova configurazione
echo -e "${BLUE}   Installazione configurazione...${NC}"
cp "$SCRIPT_DIR/rsyslog/99-mikrotik.conf" "$RSYSLOG_CONF"
chmod 644 "$RSYSLOG_CONF"

# 4. Crea directory log
echo -e "${BLUE}   Creazione directory log...${NC}"
mkdir -p "$LOG_DIR"
chown ids:ids "$LOG_DIR"
chmod 755 "$LOG_DIR"

# 5. Crea file raw.log iniziale
touch "$LOG_DIR/raw.log"
chown ids:ids "$LOG_DIR/raw.log"
chmod 644 "$LOG_DIR/raw.log"

# 6. Verifica sintassi rsyslog
echo -e "${BLUE}   Verifica sintassi...${NC}"
if rsyslogd -N1 2>&1 | grep -i "error" | grep -v "error during parsing.*mikrotik"; then
    echo -e "${RED}❌ Errori nella configurazione rsyslog${NC}"
    rsyslogd -N1
    exit 1
fi

echo -e "${GREEN}✅ Configurazione rsyslog valida${NC}"

# 7. Configura firewall per UDP:514
echo -e "${BLUE}   Configurazione firewall...${NC}"
if command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=514/udp --zone=public 2>/dev/null || true
    firewall-cmd --reload 2>/dev/null || true
    echo -e "${GREEN}✅ Firewall configurato (UDP:514)${NC}"
fi

# 8. Riavvia rsyslog
echo -e "${BLUE}   Riavvio rsyslog...${NC}"
systemctl restart rsyslog
systemctl enable rsyslog

# 9. Verifica servizio attivo
if systemctl is-active --quiet rsyslog; then
    echo -e "${GREEN}✅ rsyslog attivo e in ascolto su UDP:514${NC}"
else
    echo -e "${RED}❌ rsyslog non attivo${NC}"
    systemctl status rsyslog
    exit 1
fi

# 10. Verifica porta UDP:514
echo -e "${BLUE}   Verifica porta UDP:514...${NC}"
sleep 2
if netstat -ulnp | grep -q ":514"; then
    echo -e "${GREEN}✅ rsyslog in ascolto su UDP:514${NC}"
    netstat -ulnp | grep ":514"
else
    echo -e "${YELLOW}⚠  Porta UDP:514 non ancora attiva (verifica tra qualche secondo)${NC}"
fi

echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ RSYSLOG CONFIGURATO CON SUCCESSO         ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}📊 VERIFICA:${NC}"
echo -e "   • File log:     $LOG_DIR/raw.log"
echo -e "   • Configurazione: $RSYSLOG_CONF"
echo -e "   • Porta:        UDP:514"
echo ""
echo -e "${BLUE}🧪 TEST:${NC}"
echo -e "   # Invia log test dal router MikroTik:"
echo -e "   /system logging action set remote=<IP_SERVER> remote-port=514"
echo -e ""
echo -e "   # Monitora log in arrivo:"
echo -e "   tail -f $LOG_DIR/raw.log"
echo ""
