#!/bin/sh
# sshg-fw-iptables
# This file is part of SSHGuard.

run_iptables() {
    cmd=iptables
    if [ "6" = "$2" ]; then
        cmd=ip6tables
    fi

    # Check if iptables supports the '-w' flag.
    if $cmd -w -V >/dev/null 2>&1; then
        $cmd -w $1
    else
        $cmd $1
    fi
}

fw_init() {
    run_iptables "-L -n"
}

fw_block() {
    run_iptables "-I sshguard -s $1/$3 -j DROP" $2
}

fw_release() {
    run_iptables "-D sshguard -s $1/$3 -j DROP" $2
}

fw_flush() {
    run_iptables "-F sshguard" 4
    run_iptables "-F sshguard" 6
}

fw_fin() {
    :
}
die() {
    echo "`basename $0`: $2" >&2
    exit $1
}

fw_init || die 69 "Could not initialize firewall"

cleanup() {
    trap "" EXIT
    if [ "YES" = "$flushonexit" ]; then
        fw_flush
    fi
    fw_fin
    exit
}

trap cleanup EXIT INT TERM

while read cmd address addrtype cidr; do
    case $cmd in
        block)
            fw_block $address $addrtype $cidr;;
        release)
            fw_release $address $addrtype $cidr;;
        flush)
            fw_flush;;
        flushonexit)
            flushonexit=YES;;
        *)
            die 65 "Invalid command";;
    esac
done
