#!/usr/bin/env bash
# zeek.sh - install/remove Zeek IDS on Debian 13 (trixie) from the OBS repo
# Usage: sudo ./zeek.sh add|remove|status   (IFACE=eth1 ./zeek.sh add to override iface)

set -euo pipefail

IFACE="${IFACE:-eth0}"
[[ $IFACE =~ ^[A-Za-z0-9._@:-]+$ ]] || { echo "invalid IFACE" >&2; exit 1; }
ZEEK_ROOT=/opt/zeek
REPO_LIST=/etc/apt/sources.list.d/zeek.list
KEYRING=/etc/apt/keyrings/zeek-obs.gpg
KEY_URL=https://download.opensuse.org/repositories/security:/zeek/Debian_13/Release.key
UNIT=/etc/systemd/system/zeek.service
PRUNE_UNIT=/etc/systemd/system/zeek-log-prune.service
PRUNE_TIMER=/etc/systemd/system/zeek-log-prune.timer

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

usage() {
    echo "Usage: $0 {add|remove|status}"
    exit 2
}

add() {
    echo "[*] Installing prerequisites"
    export DEBIAN_FRONTEND=noninteractive
    apt-get update -y || true
    apt-get install -y ca-certificates curl gnupg

    echo "[*] Fetching and dearmoring Zeek OBS repo key -> ${KEYRING}"
    install -d -m 0755 /etc/apt/keyrings
    curl -fsSL "${KEY_URL}" | gpg --dearmor --yes -o "${KEYRING}"
    chmod 0644 "${KEYRING}"

    echo "[*] Writing ${REPO_LIST}"
    cat > "${REPO_LIST}" <<EOF
deb [signed-by=${KEYRING}] https://download.opensuse.org/repositories/security:/zeek/Debian_13/ /
EOF

    echo "[*] apt-get update"
    apt-get update -y || true

    echo "[*] Installing zeek + zeekctl"
    if ! apt-get install -y zeek zeekctl; then
        echo "[!] 'zeek zeekctl' failed; trying 'zeek' alone"
        apt-get install -y zeek
    fi

    echo "[*] Writing minimal standalone node.cfg (af_packet on ${IFACE})"
    cat > "${ZEEK_ROOT}/etc/node.cfg" <<EOF
# Managed by zeek.sh - minimal standalone node
[zeek]
type = standalone
host = localhost
interface = ${IFACE}
af_packet_fanout = no
EOF

    echo "[*] zeekctl deploy"
    "${ZEEK_ROOT}/bin/zeekctl" deploy

    echo "[*] Creating ${UNIT}"
    cat > "${UNIT}" <<'EOF'
[Unit]
Description=Zeek network security monitor (via zeekctl)
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/opt/zeek/bin/zeekctl start
ExecStop=/opt/zeek/bin/zeekctl stop

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable --now zeek.service

    echo "[*] Installing daily log-prune timer (zeek-log-prune.timer, >14 days)"
    cat > "${PRUNE_UNIT}" <<'EOF'
[Unit]
Description=Prune Zeek logs older than 14 days

[Service]
Type=oneshot
ExecStart=/usr/bin/find /opt/zeek/logs -mindepth 1 -maxdepth 1 -type d -mtime +14 -exec rm -rf {} +
EOF

    cat > "${PRUNE_TIMER}" <<'EOF'
[Unit]
Description=Run Zeek log pruning daily

[Timer]
OnCalendar=daily
Persistent=true

[Install]
WantedBy=timers.target
EOF
    systemctl daemon-reload
    systemctl enable --now zeek-log-prune.timer

    echo "[+] Zeek installed; logs in ${ZEEK_ROOT}/logs"
}

remove() {
    echo "[*] Stopping Zeek"
    if [[ -x ${ZEEK_ROOT}/bin/zeekctl ]]; then
        "${ZEEK_ROOT}/bin/zeekctl" stop 2>/dev/null || true
    fi
    systemctl disable --now zeek.service 2>/dev/null || true
    rm -f "${UNIT}"
    systemctl disable --now rita-import.timer 2>/dev/null || true
    rm -f /etc/systemd/system/rita-import.{service,timer}
    systemctl disable --now zeek-log-prune.timer 2>/dev/null || true
    rm -f "${PRUNE_UNIT}" "${PRUNE_TIMER}"
    systemctl daemon-reload

    echo "[*] Purging zeek packages"
    export DEBIAN_FRONTEND=noninteractive
    apt-get purge -y zeek zeekctl 2>/dev/null || true

    echo "[*] Removing repo file, keyring and ${ZEEK_ROOT}"
    rm -f "${REPO_LIST}" "${KEYRING}"
    rm -rf "${ZEEK_ROOT}"

    echo "[*] apt-get autoremove --purge"
    apt-get autoremove --purge -y

    echo "[+] Zeek removed"
}

status() {
    echo "[*] zeek.service:"
    systemctl is-active zeek.service 2>/dev/null && systemctl is-enabled zeek.service 2>/dev/null || echo "inactive/not installed"
    echo "[*] zeekctl status:"
    if [[ -x ${ZEEK_ROOT}/bin/zeekctl ]]; then
        "${ZEEK_ROOT}/bin/zeekctl" status 2>/dev/null || true
    else
        echo "zeekctl not installed"
    fi
    echo "[*] Logs: ${ZEEK_ROOT}/logs"
    ls "${ZEEK_ROOT}/logs" 2>/dev/null | tail -n 5 || true
}

case "${1:-}" in
    add)    add ;;
    remove) remove ;;
    status) status ;;
    *)      usage ;;
esac
