#!/bin/bash

# Script per configurare crontab per il sistema IDS
# Eseguire con: chmod +x setup_crontab.sh && sudo ./setup_crontab.sh

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

echo -e "${BLUE}🔧 CONFIGURAZIONE CRONTAB SISTEMA IDS${NC}"
echo "=================================================="

# Rileva percorso corrente
IDS_DIR="/opt/ids"
echo -e "${YELLOW}📁 Directory IDS: ${IDS_DIR}${NC}"

# Percorsi dei log
TRAINING_LOG="/var/log/ids/training.log"
DETECT_LOG="/var/log/ids/detect.log"
FRONTEND_LOG="/var/log/ids/frontend.log"
BACKEND_LOG="/var/log/ids/backend.log"
CRON_LOG="/var/log/ids/cron.log"

# Crea directory log
mkdir -p /var/log/ids
chown -R ids:ids /var/log/ids

echo -e "${YELLOW}📄 Log files:${NC}"
echo -e "   • Training: ${TRAINING_LOG}"
echo -e "   • Detection: ${DETECT_LOG}"
echo -e "   • Frontend: ${FRONTEND_LOG}"
echo -e "   • Backend Python: ${BACKEND_LOG}"
echo -e "   • Crontab: ${CRON_LOG}"

# Crea backup del crontab esistente
echo -e "\n${BLUE}💾 Backup crontab esistente...${NC}"
crontab -u ids -l > /tmp/crontab_backup_$(date +%Y%m%d_%H%M%S) 2>/dev/null || echo "Nessun crontab esistente"

# Crea il nuovo crontab
echo -e "\n${BLUE}⚙️  Configurazione nuovo crontab...${NC}"

cat > /tmp/new_crontab << EOF
# ============================================
# SISTEMA IDS - CONFIGURAZIONE AUTOMATICA
# ============================================

# Training ML ogni 12 ore (alle 00:00 e 12:00)
0 */12 * * * ${IDS_DIR}/deployment/cron_train.sh

# Detection automatica ogni 5 minuti
*/5 * * * * ${IDS_DIR}/deployment/cron_detect.sh

# Verifica processo backend Python ogni 5 minuti (riavvia se non attivo)
*/5 * * * * ${IDS_DIR}/deployment/check_backend.sh >> ${CRON_LOG} 2>&1

# Verifica processo frontend ogni 5 minuti (riavvia se non attivo)
*/5 * * * * ${IDS_DIR}/deployment/check_frontend.sh >> ${CRON_LOG} 2>&1

# Pulizia log settimanale (ogni domenica alle 02:00)
0 2 * * 0 find /var/log/ids -name "*.log" -size +100M -exec truncate -s 50M {} \; >> ${CRON_LOG} 2>&1

# Restart completo del sistema ogni settimana (domenica alle 03:00)
0 3 * * 0 ${IDS_DIR}/deployment/restart_all.sh >> ${CRON_LOG} 2>&1

# Backup database giornaliero (alle 04:00)
0 4 * * * ${IDS_DIR}/deployment/backup_db.sh >> ${CRON_LOG} 2>&1
EOF

# Installa il nuovo crontab
crontab -u ids /tmp/new_crontab

echo -e "${GREEN}✅ Crontab configurato con successo!${NC}"

# Rendi eseguibili gli script esistenti
chmod +x ${IDS_DIR}/deployment/cron_train.sh
chmod +x ${IDS_DIR}/deployment/cron_detect.sh
chmod +x ${IDS_DIR}/deployment/check_backend.sh
chmod +x ${IDS_DIR}/deployment/check_frontend.sh
chmod +x ${IDS_DIR}/deployment/restart_all.sh
chmod +x ${IDS_DIR}/deployment/backup_db.sh

# Avvio immediato dei processi
echo -e "\n${BLUE}🚀 Avvio immediato dei processi...${NC}"
sudo -u ids ${IDS_DIR}/deployment/check_backend.sh
sudo -u ids ${IDS_DIR}/deployment/check_frontend.sh

echo -e "\n${GREEN}✅ CONFIGURAZIONE COMPLETATA!${NC}"
echo ""
echo -e "${YELLOW}📋 COMANDI UTILI:${NC}"
echo -e "   • Visualizza log backend:    ${BLUE}tail -f ${BACKEND_LOG}${NC}"
echo -e "   • Visualizza log frontend:   ${BLUE}tail -f ${FRONTEND_LOG}${NC}"
echo -e "   • Visualizza log training:   ${BLUE}tail -f ${TRAINING_LOG}${NC}"
echo -e "   • Visualizza log detection:  ${BLUE}tail -f ${DETECT_LOG}${NC}"
echo -e "   • Stato crontab:             ${BLUE}crontab -u ids -l${NC}"
echo -e "   • Stato processi:            ${BLUE}ps aux | grep -E 'python.*main|npm.*dev'${NC}"
echo -e "   • Restart manuale:           ${BLUE}sudo ${IDS_DIR}/deployment/restart_all.sh${NC}"
echo ""
echo -e "${YELLOW}⚠️  IMPORTANTE:${NC}"
echo -e "   • Training automatico ogni 12 ore"
echo -e "   • Detection automatica ogni 5 minuti"
echo -e "   • Monitoring processi ogni 5 minuti"
echo -e "   • Restart automatico ogni domenica alle 03:00"
echo -e "   • Backup database giornaliero alle 04:00"
echo ""
echo -e "${GREEN}🎉 Sistema IDS configurato per l'esecuzione automatica!${NC}"
