#!/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_ipt()
{
	[ -f "$statefile" ] && die "state file $statefile already exists"

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

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

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

	rm -f "$statefile"

	echo "PASS" > $outfile
}

do_start_nft()
{
	[ -f "$statefile" ] && die "state file $statefile already exists"

	do_or_fail "can't install a state match" \
		nft add rule filter INPUT \
		ct state related,established accept

	do_or_fail "can't list the loaded nftables" \
		nft list ruleset \> "$statefile"
}

do_stop_nft()
{
	do_or_fail "can't compare the nftables" \
		nft list ruleset \| diff -u "$statefile" -

	rm -f "$statefile"

	echo "PASS" > $outfile
}

do_start()
{
	[ -x "$(command -v nft)" ] && do_start_nft || do_start_ipt
}

do_stop()
{
	[ -x "$(command -v nft)" ] && do_stop_nft || do_stop_ipt
}

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 already exists"

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