#!/bin/sh
ORIG_IFS=$IFS

# 1st flush & clear out the non-filter chains
#
# WARNING: If you use the nat table for anything (i.e. the WH database) 
#	   then this will break those rules!  Make sure this script runs 
#	   beforehand.  For example, have it run just prior to starting 
#	   Docker via systemd and then your other rules go into rc.local
#
for TABLE in nat mangle raw; do
	iptables -v -t $TABLE -F
	CHAINS=$(iptables -t $TABLE -L | egrep '^Chain' | awk '{print $2}' | egrep --color=never '(KUBE|DOCKER|cali)($|\-)')
	for C in $CHAINS; do iptables -v -t $TABLE -X $C; done
done

# Filter chain will be a bit harder - 1st flush the forward chain
iptables -v -F FORWARD

# Then go through the others deleting them after removing anything 
# that refers to them
DELETE_CHAINS=$(iptables -L | egrep '^Chain' | awk '{print $2}' | egrep --color=never '(KUBE|DOCKER|cali)($|\-)')
for DC in $DELETE_CHAINS; do
	CHAINS=$(iptables -L | egrep '^Chain' | awk '{print $2}')
	iptables -v -F $DC
	for C in $CHAINS; do if [ "$C" != "$DC" ]; then
		for L in $(iptables --line-numbers -L $C | egrep "(^| )${DC}($| )" | awk '{print $1}'); do
			iptables -v -D $C $L
		done
	fi; done
	iptables -v -X $DC
done
