#!/bin/bash
# Install IDS Systemd Services
# Run this script with sudo on the AlmaLinux server

set -e

echo "========================================="
echo "IDS Systemd Services Installation"
echo "========================================="

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
  echo "Error: This script must be run as root (use sudo)"
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo ""
echo "Installing systemd service files..."

# Copy service files
cp "$PROJECT_ROOT/deployment/systemd/ids-backend.service" /etc/systemd/system/
cp "$PROJECT_ROOT/deployment/systemd/ids-ml-backend.service" /etc/systemd/system/
cp "$PROJECT_ROOT/deployment/systemd/ids-syslog-parser.service" /etc/systemd/system/
cp "$PROJECT_ROOT/deployment/systemd/ids-auto-block.service" /etc/systemd/system/

# Ensure correct permissions
chmod 644 /etc/systemd/system/ids-backend.service
chmod 644 /etc/systemd/system/ids-ml-backend.service
chmod 644 /etc/systemd/system/ids-syslog-parser.service
chmod 644 /etc/systemd/system/ids-auto-block.service

echo "Service files copied to /etc/systemd/system/"

echo ""
echo "Reloading systemd daemon..."
systemctl daemon-reload

echo ""
echo "Enabling services to start on boot..."
systemctl enable ids-backend.service
systemctl enable ids-ml-backend.service
systemctl enable ids-syslog-parser.service

echo ""
echo "========================================="
echo "Installation Complete!"
echo "========================================="
echo ""
echo "Next steps:"
echo ""
echo "1. Start the services:"
echo "   sudo systemctl start ids-backend"
echo "   sudo systemctl start ids-ml-backend"
echo "   sudo systemctl start ids-syslog-parser"
echo ""
echo "2. Check status:"
echo "   sudo systemctl status ids-backend ids-ml-backend ids-syslog-parser"
echo ""
echo "3. View logs:"
echo "   tail -f /var/log/ids/backend.log"
echo "   tail -f /var/log/ids/ml_backend.log"
echo "   tail -f /var/log/ids/syslog_parser.log"
echo ""
echo "Services are now configured with auto-restart (Restart=always)"
echo "They will automatically restart on crash and at system boot."
echo ""
