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

fw_init() {
    pfctl -q -t sshguard -T show > /dev/null
}

fw_block() {
    pfctl -q -k $1 -t sshguard -T add $1/$3
}

fw_release() {
    pfctl -q -t sshguard -T del $1/$3
}

fw_flush() {
    pfctl -q -t sshguard -T flush
}

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
