#!/bin/sh

ifname=$(uci show network | grep -E '\.proto=' | grep -E 'pppoe|l2tp|pptp' | awk -F'[.=]' '{print $2}')
server=$(uci get network.$ifname.server 2>/dev/null)
ns_list=$(awk '/^nameserver/ {print $2}' /tmp/resolv.conf.d/resolv.conf.auto)

if [ -n "$server" ] && [ -n "$ns_list" ]; then
	echo "$server" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' && exit 0
	[ -d /tmp/dnsmasq.d ] || mkdir -p /tmp/dnsmasq.d
	echo -n > /tmp/dnsmasq.d/isp.servers
	echo "rebind-domain-ok=$server" >> /tmp/dnsmasq.d/isp.servers
	echo "$ns_list" | while read dns; do
		if [ -n "$dns" ]; then
			echo "server=/$server/$dns" >> /tmp/dnsmasq.d/isp.servers
		fi
	done
	/etc/init.d/dnsmasq restart
fi
