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

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

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

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

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

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