#!/bin/sh
# R-VPN Lite for routers: while the tunnel is up, the home network's DNS goes through it too.
# rvpn-router runs «rvpn-hook up» when the tunnel comes up and «rvpn-hook down» when it stops; the service
# runs «down» on start and stop. dnsmasq includes every file of its conf-dir (/tmp, nothing on flash).
TUNNEL_DNS=10.67.0.2
# -X: the real section names (cfg01411c), as dnsmasq's init names its conf-dir; without it uci shows
# «@dnsmasq[0]» and the file landed in a folder dnsmasq never reads (the LAN's DNS went past the tunnel).
confdirs() {
	uci -q -X show dhcp | sed -n 's/^dhcp\.\([^.=]*\)=dnsmasq$/\1/p' | while read -r cfg; do
		dir=$(uci -q get "dhcp.$cfg.confdir")
		echo "${dir:-/tmp/dnsmasq.$cfg.d}" | cut -d, -f1
	done
}
case "$1" in
up)
	for d in $(confdirs); do
		mkdir -p "$d" && printf 'no-resolv\nserver=%s\n' "$TUNNEL_DNS" > "$d/rvpn.conf"
	done
	;;
down)
	changed=
	for d in $(confdirs); do
		[ -f "$d/rvpn.conf" ] && rm -f "$d/rvpn.conf" && changed=1
	done
	[ -n "$changed" ] || exit 0
	;;
*)
	echo "usage: rvpn-hook up|down" >&2
	exit 2
	;;
esac
/etc/init.d/dnsmasq restart >/dev/null 2>&1
exit 0
