#!/bin/sh
set -eu

TOOLSUFFIX="${TOOLSUFFIX:--legacy}"

setup_config() {
    rm -f /etc/ferm/ferm.conf
    cat >> /etc/ferm/ferm.conf <<'EOF'
table filter {
    chain INPUT {
        policy ACCEPT;
        mod state state INVALID DROP;
    }
}
EOF
}

flush() {
    ferm --flush/etc/ferm/ferm.conf 2>/dev/null || true
    iptables-legacy --flush 2>/dev/null || true
    iptables-nft --flush
    nft flush ruleset
    modprobe -r iptable_filter
}

check_present() {
    if iptables${TOOLSUFFIX:-}-save 2>/dev/null | grep -q "state INVALID"; then
        return 0
    fi

    if nft list ruleset 2>/dev/null | grep -qi "invalid"; then
        return 0
    fi

    echo "ERROR: firewall rule not present"
    systemctl status ferm.service --no-pager || true
    iptables${TOOLSUFFIX:-}-save
    nft list ruleset
    exit 1
}

check_absent() {
    if iptables${TOOLSUFFIX:-}-save 2>/dev/null | grep -q "state INVALID"; then
        echo "ERROR: firewall rule still present (iptables-legacy)"
        iptables${TOOLSUFFIX:-}-save
        exit 1
    fi

    if nft list ruleset 2>/dev/null | grep -qi "invalid"; then
        echo "ERROR: firewall rule still present (nft)"
        nft list ruleset
        exit 1
    fi
}
