#!/bin/sh
#  /usr/sbin/firewall
# 
#  Copyright: ©2015, Güralp Systems Ltd.
#  Author: Laurence Withers <lwithers@guralp.com>
#  License: GPLv3
#
#  Firewall control script.
#

SAVE4="/etc/iptables/rules"
SAVE6="/etc/iptables/6rules"

if [ "$(id -u)" != "0" ]
then
    echo "You must be root in order to manipulate the firewall."
    exit 1
fi

usage() {
    cat <<EOF
Usage:

    The firewall rules are manipulated using the "iptables" and "ip6tables"
    commands.

    /usr/sbin/firewall save
        Saves any rules that were added or modified to persistent storage.
        This happens automatically on a clean reboot, but not on an
        unexpected reboot/power outage.

    /usr/sbin/firewall reload
        Reloads the rules from the last time they were saved to persistent
        storage.

    /usr/sbin/firewall clear
        Completely clears the firewall of all rules, so that all connections
        will be accepted. Does not save to persistent storage.
EOF
}

if [ "$#" -ne 1 ]
then
    usage
    exit 1
fi

case "$1" in
help|--help|-h)
    usage
    exit 0
    ;;

save)
    echo "Saving IPv4 firewall rules..."
    iptables-save > "${SAVE4}.new" && mv "${SAVE4}.new" "${SAVE4}"
    echo "Saving IPv6 firewall rules..."
    ip6tables-save > "${SAVE6}.new" && mv "${SAVE6}.new" "${SAVE6}"
    ;;

reload)
    if [ -r "${SAVE4}" ]
    then
        echo "Restoring IPv4 firewall rules..."
        iptables-restore < "${SAVE4}"
    fi
    if [ -r "${SAVE6}" ]
    then
        echo "Restoring IPv6 firewall rules..."
        ip6tables-restore < "${SAVE6}"
    fi
    ;;

clear)
    echo "Clearing firewall rules..."
    set -x
    iptables -P INPUT ACCEPT
    iptables -P FORWARD ACCEPT
    iptables -P OUTPUT ACCEPT
    iptables -F
    iptables -X
    ip6tables -P INPUT ACCEPT
    ip6tables -P FORWARD ACCEPT
    ip6tables -P OUTPUT ACCEPT
    ip6tables -F
    ip6tables -X
    set +x
    echo "*"
    echo "* Firewall rules are cleared"
    echo "*"
    ;;

*)
    echo "Unrecognised command. Try \"$0 help\"."
    exit 1
esac

# vim: ts=4:sw=4:expandtab
