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

fw_init() {
    ipset -quiet create -exist sshguard4 hash:net family inet
    ipset -quiet create -exist sshguard6 hash:net family inet6
}

fw_block() {
    ipset -quiet add -exist sshguard$2 $1/$3
}

fw_release() {
    ipset -quiet del -exist sshguard$2 $1/$3
}

fw_flush() {
    ipset -quiet flush sshguard4
    ipset -quiet flush sshguard6
}

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 -r 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
