#!/bin/bash

appCrowdSecVerifyFirewall() {
    echo "=== nftables tables present ==="
    runSystem nft list tables 2>&1
    echo
    echo "=== chain priorities (input hook) ==="
    runSystem nft list ruleset 2>/dev/null | grep -E 'chain |hook input.*priority' | head -30
    echo
    echo "=== priority comparison ==="
    local cs_prio ufw_prio
    cs_prio=$(runSystem nft list ruleset 2>/dev/null | awk '/table .* crowdsec/{flag=1} flag && /priority/{match($0,/priority [-0-9]+/); print substr($0,RSTART+9,RLENGTH-9); exit}')
    ufw_prio=$(runSystem nft list ruleset 2>/dev/null | awk '/chain ufw[a-z0-9-]*input/{flag=1} flag && /priority/{match($0,/priority [-0-9]+/); print substr($0,RSTART+9,RLENGTH-9); exit}')

    echo "CrowdSec priority: ${cs_prio:-not present}"
    echo "UFW priority:      ${ufw_prio:-not present}"

    if [[ -z "$cs_prio" ]]; then
        isNotice "CrowdSec nftables table missing — bouncer may not be running."
        runSystem systemctl is-active crowdsec-firewall-bouncer
        return 1
    fi
    if [[ -z "$ufw_prio" ]]; then
        isSuccessful "UFW not in nftables — no ordering needed."
        return 0
    fi
    if [[ "$cs_prio" -lt "$ufw_prio" ]]; then
        isSuccessful "Order is correct: CrowdSec ($cs_prio) runs before UFW ($ufw_prio)."
    else
        isNotice "WARNING: CrowdSec ($cs_prio) does not run before UFW ($ufw_prio). Run the 'crowdsec_fix_priority' Tools action to fix."
        return 1
    fi
}
