#!/usr/bin/env bash
# suricata-ntopng.sh - feed Suricata eve.json into a second ntopng instance (port 3002)
# Usage: sudo ./suricata-ntopng.sh enable|disable|status

set -euo pipefail

UNIT=/etc/systemd/system/ntopng-suricata.service
EVE=/var/log/suricata/eve.json
STATE_DIR=/var/lib/ntopng-suricata

# Re-exec with sudo if not root
if [[ ${EUID} -ne 0 ]]; then
    exec sudo -E "$0" "$@"
fi

usage() {
    echo "Usage: $0 {enable|disable|status}"
    exit 2
}

enable() {
    if [[ ! -x /usr/bin/ntopng || ! -x /usr/bin/suricata ]]; then
        echo "[!] add ntopng and suricata first" >&2
        exit 1
    fi

    echo "[*] Creating ${UNIT}"
    cat > "${UNIT}" <<EOF
[Unit]
Description=ntopng reading Suricata eve.json
After=suricata.service
Requires=suricata.service

[Service]
ExecStart=/usr/bin/ntopng -i ${EVE} -w 3002 -d ${STATE_DIR}
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

    systemctl daemon-reload
    systemctl enable --now ntopng-suricata.service
    if ! systemctl is-active --quiet ntopng-suricata.service; then
        echo "[!] ntopng-suricata.service failed to start; check 'journalctl -u ntopng-suricata.service'" >&2
        exit 1
    fi
    echo "[+] ntopng-suricata enabled (web UI on port 3002)"
}

disable() {
    echo "[*] Stopping and disabling ntopng-suricata.service"
    systemctl stop ntopng-suricata.service 2>/dev/null || true
    systemctl disable ntopng-suricata.service 2>/dev/null || true

    echo "[*] Removing unit and state dir"
    rm -f "${UNIT}"
    rm -rf "${STATE_DIR}"
    systemctl daemon-reload

    echo "[+] ntopng-suricata disabled"
}

status() {
    echo "[*] ntopng-suricata service:"
    systemctl is-active ntopng-suricata.service 2>/dev/null && systemctl is-enabled ntopng-suricata.service 2>/dev/null || echo "inactive/not enabled"
    echo "[*] Port 3002:"
    if ss -ltn 2>/dev/null | grep -q ':3002 '; then
        echo "listening"
    else
        echo "not listening"
    fi
}

case "${1:-}" in
    enable)  enable ;;
    disable) disable ;;
    status)  status ;;
    *)       usage ;;
esac
