#!/bin/sh
set -eu

TOOLSUFFIX="${TOOLSUFFIX:-}"

setup_config() {
    rm -f /etc/ferm/ferm.conf
    if [ -n "${TOOLSUFFIX:-}" ]; then
        cat > /etc/ferm/ferm.conf <<EOF
@def \$path_iptables= "/usr/sbin/iptables$TOOLSUFFIX";
@def \$path_iptables_save="/usr/sbin/iptables$TOOLSUFFIX-save";
@def \$path_iptables_restore="/usr/sbin/iptables$TOOLSUFFIX-restore";
@def \$path_ip6tables= "/usr/sbin/ip6tables$TOOLSUFFIX";
@def \$path_ip6tables_save="/usr/sbin/ip6tables$TOOLSUFFIX-save";
@def \$path_ip6tables_restore="/usr/sbin/ip6tables$TOOLSUFFIX-restore";
EOF
    fi
    cat >> /etc/ferm/ferm.conf <<'EOF'
domain (ip ip6) {
    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
    ip6tables-legacy --flush 2>/dev/null || true
    iptables-nft --flush 2>/dev/null || true
    ip6tables-nft --flush 2>/dev/null || true
    nft flush ruleset
    modprobe -r iptable_filter
}

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

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

    echo >&2 "ERROR (check_present): firewall rule not present"
    systemctl status ferm.service --no-pager || true
    iptables${TOOLSUFFIX:-}-save
    ip6tables${TOOLSUFFIX:-}-save
    nft list ruleset 2>/dev/null
    exit 1
}

show() {
    echo "---- show ${1:-} ----"
    echo "iptables-nft -nvL"
    iptables-nft -nvL 2>/dev/null
    ip6tables-nft -nvL 2>/dev/null
    echo "iptables-legacy -nvL"
    iptables-legacy -nvL 2>/dev/null
    ip6tables-legacy -nvL 2>/dev/null
    echo "nft list ruleset"
    nft list ruleset 2>/dev/null
    echo "---- end show ${1:-} ----"
}


check_absent() {
    if iptables${TOOLSUFFIX:-}-save 2>/dev/null | grep -q "state INVALID"; then
        if ip6tables${TOOLSUFFIX:-}-save 2>/dev/null | grep -q "state INVALID"; then
            echo >&2 "ERROR (check_absent): firewall rule still present (iptables${TOOLSUFFIX:-})"
            iptables${TOOLSUFFIX:-}-save
            ip6tables${TOOLSUFFIX:-}-save
            systemctl status ferm.service --no-pager || true
            exit 1
        fi
    fi

    if nft list ruleset 2>/dev/null | grep -qi "invalid"; then
        echo >&2 "ERROR (check_absent): firewall rule still present (nft)"
        nft list ruleset 2>/dev/null
        systemctl status ferm.service --no-pager || true
        exit 1
    fi
}
