#!/bin/sh

if id | grep root 2>&1 > /dev/null
then
	echo "Got root"
else
	exec sudo $0 $*
fi

usage() {
	echo "Usage: $0 [-ud] <downstream-interface> <upstream-interface>"
	exit 1
}

# one of these days, port to:
# nft add table nat
# nft add chain nat postrouting { type nat hook postrouting priority 100 \; }
# nft add rule nat postrouting ip saddr 192.168.1.0/24 oif wlan0 masquerade

start() {
	echo 1 > /proc/sys/net/ipv4/ip_forward
	iptables -t nat -A POSTROUTING -o $upstream -j MASQUERADE
	iptables -A FORWARD -i $upstream -o $downstream -m state \
		--state RELATED,ESTABLISHED -j ACCEPT
	iptables -A FORWARD -i $downstream -o $upstream -j ACCEPT
	# I'm doing dhcpd management on the downstrem interface.  Otherwise:
	#dhcpd $downstream
}

stop() {
	#killall dhcpd
	iptables -t nat -D POSTROUTING -o $upstream -j MASQUERADE
	iptables -D FORWARD -i $upstream -o $downstream -m state \
		--state RELATED,ESTABLISHED -j ACCEPT
	iptables -D FORWARD -i $downstream -o $upstream -j ACCEPT
}

interactive() {
	start
	echo -n "Return to tear down forward"
	read x
	stop
}

action=interactive

while getopts "ud" option; do
	case $option in
		u)
			action=start
			;;
		d)
			action=stop
			;;
		*)
			usage
	esac
done
shift $((OPTIND-1))

downstream=$1
upstream=$2

if [ "t$downstream" = t -o "t$upstream" = t ] ; then
	usage
fi

$action


