#!/bin/sh

match_or_exit () {
	file_to_match="$1"
	pattern_file="$2"

	while read line_to_match <&3 && read pattern_line <&4 ; do
		if [ "${line_to_match##$pattern_line}" ]; then
			echo '!!! MISMATCH !!!' >&2
			echo "Line:    ${line_to_match}" >&2
			echo "Pattern: ${pattern_line}" >&2
			exit 1
		fi;
	done 3<"${file_to_match}" 4<"${pattern_file}"
}

echo 'vvv systemctl status arno-iptables-firewall.service vvv'
systemctl status arno-iptables-firewall.service
echo '^^^ systemctl status arno-iptables-firewall.service ^^^'

echo 'vvv journalctl vvv'
journalctl
echo '^^^ journalctl ^^^'

echo 'vvv iptables -S vvv'
iptables -S 2>/dev/null
echo '^^^ iptables -S ^^^'

echo 'vvv ip6tables -S vvv'
ip6tables -S 2>/dev/null
echo '^^^ ip6tables -S ^^^'

echo Checking config file for expected content ...
if ! diff /etc/arno-iptables-firewall/conf.d/00debconf.conf debian/tests/expected-config.d/00debconf.conf; then
	echo ... failed!
	exit 1
else
	echo ... succeeded!
fi

echo Checking for expected iptables rules ...
# LC_ALL=C to make sure to sort by native byte values
LC_ALL=C
iptables -S 2>/dev/null | sort -sk 2,2 >/tmp/current_iptables_-S_sorted
sort -sk 2,2 debian/tests/expected-config.d/iptables_-S >/tmp/iptables_-S_sorted
match_or_exit /tmp/current_iptables_-S_sorted /tmp/iptables_-S_sorted
echo ... succeeded!

echo Checking for expected ip6tables rules ...
# LC_ALL=C to make sure to sort by native byte values
LC_ALL=C
ip6tables -S 2>/dev/null | sort -sk 2,2 >/tmp/current_ip6tables_-S_sorted
sort -sk 2,2 debian/tests/expected-config.d/ip6tables_-S >/tmp/ip6tables_-S_sorted
match_or_exit /tmp/current_ip6tables_-S_sorted /tmp/ip6tables_-S_sorted
echo ... succeeded!
