#!/bin/bash


export PATH=$PATH:${0%/*}/../../lib

die()
{
	echo "$0:${BASH_LINENO[0]}: $*" >&2
	exit 1
}

fail()
{
	echo "FAIL: $0:${BASH_LINENO[0]}: $*" > "$outfile"
	exit 1
}

do_or_fail()
{
	local failmsg="$1" output
	shift
	output="$(eval $@ 2>&1)" ||
		fail "$failmsg: $output"
}

do_start()
{
	[ -f "$statefile" ] && die "state file $statefile aleady exists"

	do_or_fail "can't install a state match" \
		iptables -A INPUT \
		-m state --state RELATED,ESTABLISHED -j ACCEPT

	do_or_fail "can't list the loaded iptables" \
		iptables -L \> "$statefile"
}

do_stop()
{
	do_or_fail "can't compare the iptables" \
		iptables -L \| diff -u "$statefile" -

	rm -f "$statefile"

	echo "PASS" > $outfile
}

tmpargs="$(../lib/parseargs.sh --name=$0 \
		--flags-req=statefile,outfile \
		--flags-opt="start,stop" -- "$@")" ||
	die "can't parse command line"
eval "$tmpargs"

[ -f "$outfile" ] && die "out file $outfile aleady exists"

# expect "start" or "stop"
do_$1
