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

FIREW_CMD="firewall-cmd --quiet"

fw_init() {
    ${FIREW_CMD} --query-rich-rule="rule family=ipv6 source ipset=sshguard6 drop" || {
      ${FIREW_CMD} --permanent --new-ipset="sshguard6" --type="hash:net" --option="family=inet6"
      ${FIREW_CMD} --permanent --add-rich-rule="rule family=ipv6 source ipset=sshguard6 drop"
    }
    ${FIREW_CMD} --query-rich-rule="rule family=ipv4 source ipset=sshguard4 drop" || {
      ${FIREW_CMD} --permanent --new-ipset="sshguard4" --type="hash:net" --option="family=inet"
      ${FIREW_CMD} --permanent --add-rich-rule="rule family=ipv4 source ipset=sshguard4 drop"
    }
    ${FIREW_CMD} --reload
}

fw_block() {
    ${FIREW_CMD} --ipset="sshguard$2" --add-entry="$1/$3"
}

fw_release() {
    ${FIREW_CMD} --ipset="sshguard$2" --remove-entry="$1/$3"
}

fw_flush() {
    ${FIREW_CMD} --reload
}

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
