#!/bin/bash
# Setup systemd timer for analytics aggregation
# Deve essere eseguito come root

set -e

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

echo -e "${BLUE}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║   IDS Analytics Timer Setup                  ║${NC}"
echo -e "${BLUE}╚═══════════════════════════════════════════════╝${NC}"
echo ""

# Check root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}❌ Questo script deve essere eseguito come root${NC}"
    echo -e "${YELLOW}   Usa: sudo $0${NC}"
    exit 1
fi

IDS_DIR="/opt/ids"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Copy systemd files
echo -e "${BLUE}📋 Copia file systemd...${NC}"
cp "${SCRIPT_DIR}/ids-analytics-aggregator.service" /etc/systemd/system/
cp "${SCRIPT_DIR}/ids-analytics-aggregator.timer" /etc/systemd/system/

# Set permissions
chmod 644 /etc/systemd/system/ids-analytics-aggregator.service
chmod 644 /etc/systemd/system/ids-analytics-aggregator.timer

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

# Enable and start timer
echo -e "${BLUE}⚙️  Enable e start timer...${NC}"
systemctl enable ids-analytics-aggregator.timer
systemctl start ids-analytics-aggregator.timer

# Check status
echo -e "\n${BLUE}📊 Stato timer:${NC}"
systemctl status ids-analytics-aggregator.timer --no-pager

echo -e "\n${BLUE}📅 Prossime esecuzioni:${NC}"
systemctl list-timers ids-analytics-aggregator.timer --no-pager

echo -e "\n${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   ✅ ANALYTICS TIMER CONFIGURATO              ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}📝 Comandi utili:${NC}"
echo -e "   ${YELLOW}Stato timer:${NC}        sudo systemctl status ids-analytics-aggregator.timer"
echo -e "   ${YELLOW}Prossime run:${NC}       sudo systemctl list-timers"
echo -e "   ${YELLOW}Log aggregazione:${NC}   sudo journalctl -u ids-analytics-aggregator -f"
echo -e "   ${YELLOW}Test manuale:${NC}       sudo systemctl start ids-analytics-aggregator"
echo ""
