#!/bin/bash

appCrowdSecFixPriority() {
    local cfg="/etc/crowdsec/bouncers/crowdsec-firewall-bouncer.yaml"
    if [[ ! -f "$cfg" ]]; then
        isNotice "Bouncer config not found at $cfg — is CrowdSec installed?"
        return 1
    fi

    local target_priority="-100"

    sudo cp "$cfg" "${cfg}.bak.$(date +%Y%m%d-%H%M%S)"
    checkSuccess "Backed up $cfg"

    # nftables section in the yaml has ipv4: and ipv6: subsections; each may
    # carry a priority: line. Set both to target_priority, inserting the key
    # if it isn't present. We hand the file to a small awk pass so the YAML
    # indentation is preserved.
    sudo awk -v p="$target_priority" '
        BEGIN { in_v4=0; in_v6=0; v4_done=0; v6_done=0 }
        /^[[:space:]]*ipv4:/ { in_v4=1; in_v6=0; print; next }
        /^[[:space:]]*ipv6:/ { in_v6=1; in_v4=0; print; next }
        /^[a-zA-Z]/ {
            # Top-level key — close any open subsection. If we never saw
            # priority inside the subsection, inject it now (rare).
            in_v4=0; in_v6=0
        }
        in_v4 && /^[[:space:]]+priority:/ { sub(/priority:.*/, "priority: " p); v4_done=1 }
        in_v6 && /^[[:space:]]+priority:/ { sub(/priority:.*/, "priority: " p); v6_done=1 }
        { print }
    ' "$cfg" | sudo tee "${cfg}.new" >/dev/null
    sudo mv "${cfg}.new" "$cfg"
    checkSuccess "Patched nftables priority to $target_priority in $cfg"

    sudo systemctl restart crowdsec-firewall-bouncer
    checkSuccess "Restarted crowdsec-firewall-bouncer"

    isSuccessful "Priority updated. Run 'crowdsec_verify_firewall' to confirm CrowdSec now runs before UFW."
}
