#!/usr/bin/env bash
# vitables -- interactively edit the current iptables ruleset

. lib.bash || exit

case ${0##*/} in
	vi6tables)
		iptables='ip6tables';;
	vitables|*)
		iptables='iptables';;
esac

temp=$(mktemp /tmp/vitables.XXXXXXXX) || exit
orig=$(mktemp /tmp/vitables.XXXXXXXX) || exit

sudo $iptables-save > "$temp" || exit

if [[ ! -s "$temp" ]]; then
	vmsg "No tables found; iptables is probably not in use on this system." >&2
	rm -f "$temp"
	exit 1
fi

cp "$temp" "$orig"

while true; do
	${EDITOR:-vi} "$temp"
	if ! grep -qs '^[^#]' "$temp"; then
		vmsg "File empty, reload aborted" >&2
		break
	elif cmp -s "$temp" "$orig"; then
		vmsg "No changes made" >&2
		break
	elif sudo $iptables-restore < "$temp"; then
		vmsg "Rules reloaded successfully"
		break
	elif ! confirm "warning: Failed to load rules; edit again?"; then
		exit
		break
	fi
done

rm -f "$temp" "$orig"
