#!/bin/sh
#
# nd-nsm-migrate: one-time update of an already configured NSM after an
# upgrade to NDOS 1.0.5. Started by nd-nsm-migrate.service on the first boot
# where /var/lib/nsm/.nsm_configured exists and the 1.0.5 stamp does not.
#
# Every action is idempotent: on a box that is already up to date it changes
# nothing. Files carried over from the previous release by the upgrade:
#   /etc/suricata/suricata.yaml  - CPU affinity nesting, rule paths, log dir
#   /etc/suricata/update.yaml    - reload command, merged-rules keys
#   /etc/sysctl.conf             - ip_forward line written by old IPS setups
# plus the capture-port network files introduced in 1.0.5, and the
# enabled state of suricata/zeek.
#
# ND_ROOT is only for testing (prefix for all paths); empty on a device.

ROOT="${ND_ROOT:-}"

NSM_DIR="$ROOT/var/lib/nsm"
STAMP="$NSM_DIR/.migrated-1.0.5"
LOG="$NSM_DIR/migrate-1.0.5.log"
SURICATA_CONF="$ROOT/etc/suricata/suricata.yaml"
UPDATE_YAML="$ROOT/etc/suricata/update.yaml"
SYSCTL_FILE="$ROOT/etc/sysctl.conf"
ZEEK_NODECFG="$ROOT/etc/zeek/node.cfg"
NETWORK_DIR="$ROOT/etc/systemd/network"
CAPTURE_PREFIX="00-nd-capture-"
SYS_NET="$ROOT/sys/class/net"

log() {
    echo "$1" >> "$LOG"
    command -v logger >/dev/null 2>&1 && logger -t nd-nsm-migrate "$1"
    echo "$1"
}

mkdir -p "$NSM_DIR"
log "=== $(date '+%Y-%m-%d %H:%M:%S') NSM update for 1.0.5"

# --------------------------------------------------
# 1. suricata.yaml
# --------------------------------------------------
migrate_suricata_conf() {

    [ -f "$SURICATA_CONF" ] || { log "suricata.yaml: not present, skipped"; return 0; }

    if grep -q '\$AF_BLOCK' "$SURICATA_CONF"; then
        log "suricata.yaml: not rendered yet (placeholders), skipped"
        return 0
    fi

    BACKUP="$NSM_DIR/suricata.yaml.pre-1.0.5"
    [ -f "$BACKUP" ] || cp -p "$SURICATA_CONF" "$BACKUP"

    TMP=$(mktemp "$NSM_DIR/suricata.yaml.XXXXXX") || return 1

    awk '
    # a) CPU affinity: sets written as siblings of cpu-affinity (2 spaces)
    #    are moved under it (4 spaces, keys 6).
    /^  cpu-affinity:[ \t]*$/ { aff = 1; print; next }
    aff && /^  (management|worker)-cpu-set:[ \t]*$/ { print "  " $0; next }
    aff && /^    cpu:/ { print "  " $0; next }
    aff && /^  [^ ]/ { aff = 0 }

    # b) rule section: merged suricata.rules + local.rules (1.0.5 layout)
    /^default-rule-path:/ {
        print "default-rule-path: /var/lib/suricata/rules"
        print "rule-files:"
        print "  - suricata.rules"
        print "  - /etc/suricata/rules/local.rules"
        print "  - /etc/suricata/rules/nd.rules"
        skip = 1; next
    }
    skip && /^classification-file:/ { skip = 0; print "" }
    skip { next }

    # c) log directory on /data
    /^default-log-dir: \/var\/log\/suricata\/?[ \t]*$/ { print "default-log-dir: /data/nsm/suricata/"; next }
    /filename: \/var\/log\/suricata\/suricata\.log[ \t]*$/ { sub(/\/var\/log\/suricata\//, "/data/nsm/suricata/"); print; next }

    { print }

    # rule section never closed: the rest of the file would be lost
    END { if (skip) exit 3 }
    ' "$SURICATA_CONF" > "$TMP"
    RC=$?

    if [ "$RC" -eq 3 ]; then
        rm -f "$TMP"
        log "suricata.yaml: no classification-file after default-rule-path, left unchanged"
        return 1
    fi

    if [ "$RC" -ne 0 ] || [ ! -s "$TMP" ]; then
        rm -f "$TMP"
        log "suricata.yaml: update failed (awk $RC or empty output), left unchanged"
        return 1
    fi

    if cmp -s "$TMP" "$SURICATA_CONF"; then
        rm -f "$TMP"
        log "suricata.yaml: already up to date"
        return 0
    fi

    # Validate before replacing (when the suricata binary is available)
    if command -v suricata >/dev/null 2>&1 &&
       ! suricata --dump-config -c "$TMP" >/dev/null 2>&1
    then
        rm -f "$TMP"
        log "suricata.yaml: updated config failed validation, left unchanged (backup: $BACKUP)"
        return 1
    fi

    chmod 644 "$TMP"
    mv -f "$TMP" "$SURICATA_CONF"
    log "suricata.yaml: CPU affinity, rule paths and log directory updated (backup: $BACKUP)"
}

# --------------------------------------------------
# 2. update.yaml (suricata-update)
# --------------------------------------------------
migrate_update_yaml() {

    [ -f "$UPDATE_YAML" ] || { log "update.yaml: not present, skipped"; return 0; }

    BEFORE=$(cksum < "$UPDATE_YAML")

    sed -i 's|^reload-command:.*|reload-command: systemctl try-reload-or-restart suricata|' "$UPDATE_YAML"

    grep -q '^reload-command:' "$UPDATE_YAML" || \
        echo "reload-command: systemctl try-reload-or-restart suricata" >> "$UPDATE_YAML"
    grep -q '^suricata-conf:' "$UPDATE_YAML" || \
        echo "suricata-conf: /etc/suricata/suricata.yaml" >> "$UPDATE_YAML"
    grep -q '^data-directory:' "$UPDATE_YAML" || \
        echo "data-directory: /var/lib/suricata" >> "$UPDATE_YAML"

    if [ "$BEFORE" = "$(cksum < "$UPDATE_YAML")" ]; then
        log "update.yaml: already up to date"
    else
        log "update.yaml: reload command and merged-rules settings updated"
    fi
}

# --------------------------------------------------
# 3. ip_forward written by older IPS setups
# --------------------------------------------------
migrate_sysctl() {

    if [ -f "$SYSCTL_FILE" ] && grep -q '^net\.ipv4\.ip_forward' "$SYSCTL_FILE"; then
        sed -i '/^net\.ipv4\.ip_forward/d' "$SYSCTL_FILE"
        log "sysctl.conf: ip_forward line removed (forwarding stays off)"
    else
        log "sysctl.conf: no ip_forward line"
    fi

    [ -z "$ROOT" ] && sysctl -w net.ipv4.ip_forward=0 >/dev/null 2>&1
    return 0
}

# --------------------------------------------------
# 4. Capture-port network files
# --------------------------------------------------
capture_interfaces() {
    {
        # interfaces of the af-packet section only (not pcap)
        [ -f "$SURICATA_CONF" ] && awk '
            /^af-packet:/ { s = 1; next }
            s && /^[^ #]/ { s = 0 }
            s && /^ *- *interface: */ { sub(/^ *- *interface: */, ""); sub(/[ \t].*$/, ""); print }
        ' "$SURICATA_CONF"

        [ -f "$ZEEK_NODECFG" ] && sed -n 's/^interface=\(af_packet::\)\{0,1\}//p' "$ZEEK_NODECFG"
    } | grep -v -e '^$' -e '^default$' | sort -u
}

management_interfaces() {
    if [ -n "$ND_TEST_DEFAULT_DEV" ]; then
        echo "$ND_TEST_DEFAULT_DEV"
    else
        ip -4 route show default 2>/dev/null |
            awk '{ for (i = 1; i < NF; i++) if ($i == "dev") print $(i + 1) }'
    fi
}

# NIC has an IPv4 address (static, DHCP or set by option 2)
iface_has_ipv4() {
    if [ -n "$ROOT" ]; then
        echo " $ND_TEST_ADDR_DEVS " | grep -q " $1 "
    else
        [ -n "$(ip -4 -o addr show dev "$1" 2>/dev/null)" ]
    fi
}

# Name of another file in /etc/systemd/network that matches the NIC.
# A 00-nd-capture-* file would sort first and override it.
iface_network_file() {
    for f in "$NETWORK_DIR"/*.network; do
        [ -f "$f" ] || continue
        case "${f##*/}" in "$CAPTURE_PREFIX"*) continue ;; esac
        PATS=$(sed -n 's/^[ \t]*Name[ \t]*=//p' "$f")
        set -f
        for pat in $PATS; do
            case "$pat" in '!'*) continue ;; esac
            case "$1" in $pat) set +f; echo "${f##*/}"; return 0 ;; esac
        done
        set +f
    done
    return 1
}

physical_nic_count() {
    n=0
    for d in "$SYS_NET"/*; do
        [ -e "$d/device" ] || continue
        case "${d##*/}" in wl*) continue ;; esac
        n=$((n + 1))
    done
    echo "$n"
}

migrate_capture_ports() {

    if ls "$NETWORK_DIR/${CAPTURE_PREFIX}"*.network >/dev/null 2>&1; then
        log "capture ports: already configured"
        return 0
    fi

    MGMT=$(management_interfaces)

    if [ "$(physical_nic_count)" -le 1 ]; then
        log "capture ports: single NIC (shared with management), no change"
        return 0
    fi

    mkdir -p "$NETWORK_DIR"
    WRITTEN=""

    for iface in $(capture_interfaces); do

        if echo "$MGMT" | grep -qx "$iface"; then
            log "capture ports: $iface carries the default route, left unchanged"
            continue
        fi

        if iface_has_ipv4 "$iface"; then
            log "capture ports: $iface has an IPv4 address, left unchanged"
            continue
        fi

        if NETFILE=$(iface_network_file "$iface"); then
            log "capture ports: $iface is configured in $NETFILE, left unchanged"
            continue
        fi

        cat > "$NETWORK_DIR/${CAPTURE_PREFIX}${iface}.network" <<EOF
# Written by nd-nsm-migrate (1.0.5): NSM capture port.
# Up at boot, no IP address, silent on the wire.
[Match]
Name=$iface

[Link]
Promiscuous=yes
ActivationPolicy=always-up
RequiredForOnline=no

[Network]
DHCP=no
LinkLocalAddressing=no
IPv6AcceptRA=no
LLDP=no
EmitLLDP=no
EOF
        log "capture ports: $iface kept up at boot, no IP address"
        WRITTEN="$WRITTEN $iface"
    done

    [ -z "$WRITTEN" ] && log "capture ports: no capture interface to configure"

    if [ -n "$WRITTEN" ] && [ -z "$ROOT" ] && networkctl reload >/dev/null 2>&1; then
        for iface in $WRITTEN; do
            networkctl reconfigure "$iface" >/dev/null 2>&1
        done
    fi
    return 0
}

# --------------------------------------------------
# 5. NSM engines enabled at boot
# The 1.0.4 upgrader can leave suricata.service disabled on a configured box;
# then only Zeek starts after a reboot. Enable both and start them now.
# --------------------------------------------------
migrate_units() {

    [ -n "$ROOT" ] && { log "units: test mode, skipped"; return 0; }
    
    # Stopped by the operator in option 11: leave both disabled and stopped
    if [ -f "$NSM_DIR/.nsm_stopped_by_operator" ]; then
        log "units: NSM stopped by the operator; left disabled"
        return 0
    fi

    for u in suricata zeek; do
        [ "$(systemctl is-enabled "$u" 2>/dev/null)" = "enabled" ] && continue
        # --no-reload: symlinks only, no daemon-reload in the middle of boot
        if systemctl --no-reload enable "$u" >/dev/null 2>&1; then
            log "units: $u enabled at boot"
        else
            log "units: FAILED to enable $u"
            return 1
        fi
    done

    # Queued behind this unit (Before=); --no-block avoids waiting on ourselves
    systemctl start --no-block suricata zeek >/dev/null 2>&1
    log "units: suricata and zeek enabled"
    return 0
}

FAILED=""
migrate_suricata_conf  || FAILED="$FAILED suricata.yaml"
migrate_update_yaml    || FAILED="$FAILED update.yaml"
migrate_sysctl         || FAILED="$FAILED sysctl.conf"
migrate_capture_ports  || FAILED="$FAILED capture-ports"
migrate_units          || FAILED="$FAILED units"

if [ -n "$FAILED" ]; then
    # No stamp: the service runs again at the next boot.
    log "=== FAILED:$FAILED (not stamped, retried at next boot)"
    exit 1
fi

touch "$STAMP"
log "=== done"
exit 0
