#!/bin/sh
#		Written by Simon Richter <sjr@debian.org>
#		modified by Jonathan Wiltshire <jmw@debian.org>
#		with help from Christoph Anton Mitterer
#   modified by Pawel Brzozowski <pbrzozowski@mirantis.com>

rc=0

load_rules()
{
	echo "Loading iptables rules"

	#load IPv4 rules
	if [ ! -f /etc/iptables/rules.v4 ]; then
		echo "Skipping IPv4 (no rules to load)"
	else
		echo "Loading IPv4"
		iptables-restore < /etc/iptables/rules.v4 2> /dev/null
		if [ $? -ne 0 ]; then
			rc=1
		fi
	fi

	#load IPv6 rules
	if [ ! -f /etc/iptables/rules.v6 ]; then
		echo "Skipping IPv6 (no rules to load)"
	else
		echo "Loading IPv6"
		ip6tables-restore < /etc/iptables/rules.v6 2> /dev/null
		if [ $? -ne 0 ]; then
			rc=1
		fi
	fi

	exit $rc
}

save_rules()
{
	echo "Saving rules"

	#save IPv4 rules
	#need at least iptable_filter loaded:
	/sbin/modprobe -q iptable_filter
	if [ ! -f /proc/net/ip_tables_names ]; then
		echo "Skipping IPv4 (no modules loaded)"
	elif [ -x /sbin/iptables-save ]; then
		echo "Saving IPv4"
		iptables-save > /etc/iptables/rules.v4
		if [ $? -ne 0 ]; then
			rc=1
		fi
	fi

	#save IPv6 rules
	#need at least ip6table_filter loaded:
	/sbin/modprobe -q ip6table_filter
	if [ ! -f /proc/net/ip6_tables_names ]; then
		echo "Skipping IPv6 (no modules loaded)"
	elif [ -x /sbin/ip6tables-save ]; then
		echo "Saving IPv6"
		ip6tables-save > /etc/iptables/rules.v6
		if [ $? -ne 0 ]; then
			rc=1
		fi
	fi

	exit $rc
}

flush_rules()
{
	echo "Flushing rules"

	if [ ! -f /proc/net/ip_tables_names ]; then
		echo "Skipping IPv4 (no module loaded)"
	elif [ -x /sbin/iptables ]; then
		echo "Flushing IPv4"
		for param in F Z X; do /sbin/iptables -$param; done
		for table in $(cat /proc/net/ip_tables_names)
		do
			/sbin/iptables -t $table -F
			/sbin/iptables -t $table -Z
			/sbin/iptables -t $table -X
		done
		for chain in INPUT FORWARD OUTPUT
		do
			/sbin/iptables -P $chain ACCEPT
		done
	fi

	if [ ! -f /proc/net/ip6_tables_names ]; then
		echo "Skipping IPv6 (no module loaded)"
	elif [ -x /sbin/ip6tables ]; then
		echo "Flushing IPv6"
		for param in F Z X; do /sbin/ip6tables -$param; done
		for table in $(cat /proc/net/ip6_tables_names)
		do
			/sbin/ip6tables -t $table -F
			/sbin/ip6tables -t $table -Z
			/sbin/ip6tables -t $table -X
		done
		for chain in INPUT FORWARD OUTPUT
		do
			/sbin/ip6tables -P $chain ACCEPT
		done
	fi

	exit 0
}

case "$1" in
start|restart|reload|force-reload)
	load_rules
	;;
save)
	save_rules
	;;
stop)
	flush_rules
	;;
flush)
	flush_rules
	;;
*)
    echo "Usage: $0 {start|restart|reload|force-reload|save|flush}" >&2
    exit 1
    ;;
esac
