#!/bin/bash
#
# This re-implements the 'service iptables stop' command from the
# pre-systemd era, if systemd is in use. 

# If it's not (eg if /usr/bin/systemctl doesn't exist), then it just
# uses those commands.
if [ ! -x /usr/bin/systemctl ]; then
	service iptables stop
	service ip6tables stop
	grep xt_recent /proc/modules >/dev/null && rmmod xt_recent
	grep ipt_recent /proc/modules >/dev/null && rmmod ipt_recent
	exit
fi

# Systemd is in use. Find all our modules and remove them

NF_MODULES=($(lsmod | awk "/^ip6?table_|^ip6?t_|^nf_|^xt_/ {print \$1}") ip_tables ip6_tables)
NF_MODULES_COMMON=(x_tables nf_nat nf_conntrack)

rmmod_r() {
	# Unload module with all referring modules.
	# At first all referring modules will be unloaded, then the module itself.
	local mod=$1
	local ref=

	# Get referring modules.
	ref=$(lsmod | awk "/^${mod}/ { print \$4; }" | tr ',' ' ')

	# recursive call for all referring modules
	for i in $ref; do
		rmmod_r $i
	done

	# Unload module, if it's loaded.
	if grep -q "^${mod}" /proc/modules ; then
		modprobe -r $mod > /dev/null 2>&1
	fi
}

/usr/sbin/iptables -F
/usr/sbin/iptables -X
/usr/sbin/iptables -t nat -F
/usr/sbin/iptables -t nat -X
/usr/sbin/ip6tables -F
/usr/sbin/ip6tables -X

for mod in ${NF_MODULES[*]}; do
	rmmod_r $mod
done
# try to unload remaining netfilter modules used by ipv4 and ipv6
# netfilter
for mod in ${NF_MODULES_COMMON[*]}; do
	rmmod_r $mod >/dev/null
done

