#!/bin/sh

exec >> /tmp/nm-dnsmasq.out
exec 2>&1

filter() {
	/sbin/iptables -t filter "$@"
}

nat() {
	/sbin/iptables -t nat "$@"
}

iface="$1" action="$2"

cat <<EOT
=== $(date) ===
> $0 $*

EOT

set

[ "$CONNECTION_UUID" = "dd7293b3-4dd8-4a45-b3e0-e4fd82c3b463" ] || exit 0

set -x
case "$action" in
up)
	eval `echo $IP4_ADDRESS_0 | awk '{ print "cidr=" $1; }'`
	ipaddr=${cidr%/*}

	for port in 53 67 69; do
		for proto in tcp udp; do
			filter --insert INPUT --in-interface "$iface" \
				--protocol $proto --destination-port $port --jump ACCEPT
		done
	done

	filter --insert FORWARD --in-interface $iface --jump REJECT
	filter --insert FORWARD --out-interface $iface --jump REJECT

	filter --insert FORWARD --in-interface $iface --out-interface eth0 --jump ACCEPT
	filter --insert FORWARD --source $cidr --in-interface $iface --jump ACCEPT
	filter --insert FORWARD --destination $cidr --out-interface $iface --match state --state ESTABLISHED,RELATED --jump ACCEPT

	nat --insert POSTROUTING --source $cidr ! --destination $cidr --jump MASQUERADE

	set -- --conf-file --no-hosts --bind-interfaces --except-interface=lo --listen-address=$ipaddr
	set -- "$@" --enable-tftp=$iface --tftp-root=/var/lib/tftpboot
	set -- "$@" --clear-on-reload --strict-order --pid-file=/var/run/nm-dnsmasq-shared-$iface.pid
	set -- "$@" --dhcp-range=${ipaddr%.*}.10,${ipaddr%.*}.100,60m --dhcp-option=option:router,$ipaddr
	set -- "$@" --dhcp-lease-max=50 

	/usr/sbin/dnsmasq "$@"
	;;
down)
	eval `iptables-save | grep " $iface " | grep -- '-A POSTROUTING' | sed -e "s|-A|/sbin/iptables -t nat -D|"`
	eval `iptables-save | grep " $iface " | grep -- '-A FORWARD' | sed -e "s|-A|/sbin/iptables -t filter -D|"`
	kill $(cat /var/run/nm-dnsmasq-shared-$iface.pid)
	;;
esac
