#!/bin/sh
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.

set -e

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

load_rules()
{
    #load rules
    if [ ! -f /etc/nftables.conf ]; then
	echo "Warning: no rules to load"
    else
	nft -f /etc/nftables.conf
    fi
}

save_rules()
{
    #save rules
    if [ $(which nft) ]; then
	touch /etc/nftables.conf
	chmod 0640 /etc/nftables.conf
	nft list ruleset > /etc/nftables.conf
    else
	echo "Warning: missing nft, not saving"
    fi
}

flush_rules()
{
    if [ $(which nft) ]; then
	nft flush ruleset
    fi
}

case "$1" in
    start|restart|reload|force-reload)
	load_rules
	;;
    save)
	save_rules
	;;
    stop)
	# Why? because if stop is used, the firewall gets flushed for a variable
	# amount of time during package upgrades, leaving the machine vulnerable
	# It's also not always desirable to flush during purge
	echo "Automatic flushing disabled, use \"flush\" instead of \"stop\""
	;;
    flush)
	flush_rules
	;;
    *)
	echo "Usage: $0 {start|restart|reload|force-reload|save|flush}" >&2
	exit 1
	;;
esac
