#!/bin/sh

test -x /etc/init.d/S*dnsmasq && exit

. /etc/functions.sh

case $1 in
	start)
		echo "Configure resolv..."
		# Compatibility with openwrt
		ln -sf /var/etc/resolv.conf /tmp/resolv.conf
		rm -f /var/etc/resolv.conf
		WAN_DNS=$(nvram get wan_dns)
		WAN_DOMAIN=$(nvram get wan_domain)
		# No DNS: Use well known DNS servers
		test -z "$WAN_DNS" && WAN_DNS="195.50.140.250;212.222.128.68"
		:>/var/etc/resolv.conf
		IFS=\;
		for i in $WAN_DNS;do
			echo "nameserver $i">>/var/etc/resolv.conf
		done
		unset IFS
		test -n "$WAN_DOMAIN" && echo "search $WAN_DOMAIN">>/var/etc/resolv.conf

		DHCPNUM=$(nvram get dhcp_num)
		test -z "$DHCPNUM" && DHCPNUM=6
		LAN_PROTO=$(nvram get lan_proto)
		test -z "$(nvram get ff_lan_proto)" && LAN_PROTO=static
		if [ $DHCPNUM -gt 0 ] && [ "static" = "$LAN_PROTO" ]; then
			test -d /var/run || mkdir -p /var/run
			test -f /var/run/udhcpd.leases || touch /var/run/udhcpd.leases
			export NVRAM_wan_ifname
			export NVRAM_lan_ifname
			export NVRAM_lan_ifnames
			eval $(/usr/bin/netparam)
			DHCPLEASE=$(nvram get dhcp_lease)
			test -z "$DHCPLEASE" && DHCPLEASE=12h
			test "$DHCPLEASE" = "0" && DHCPLEASE=12h
			if [ "$DHCPLEASE" != "${DHCPLEASE%[hH]}" ]; then
				DHCPLEASE=$(( ${DHCPLEASE%[hH]} * 3600 ))
			elif [ "$DHCPLEASE" != "${DHCPLEASE%[mM]}" ]; then
				DHCPLEASE=$(( ${DHCPLEASE%[mM]} * 60 ))
			fi
			DHCPNET=$(echo $LANNET|cut -d'.' -f1-3)
			DHCPBEG=$(nvram get dhcp_start)
			DHCPBEG=${DHCPBEG##*.}
			test -z "$DHCPBEG" && DHCPBEG=100
			DHCPEND=$(( $DHCPBEG + $DHCPNUM ))
		cat>/var/etc/udhcpd.conf<<EOM
start 		$DHCPNET.$DHCPBEG
end		$DHCPNET.$DHCPEND
max_leases	$DHCPNUM
opt		router $LANADR
opt		subnet $LANMSK
opt		lease $DHCPLEASE
$(test -n "${WAN_DNS%;*}" && echo opt dns ${WAN_DNS%;*})
$(test -n "${WAN_DNS#*;}" && echo opt dns ${WAN_DNS#*;})
$(test -n "$WAN_DOMAIN" && echo opt domain $WAN_DOMAIN)
interface	$LANDEV
lease_file	/var/run/udhcpd.leases
$(cat /etc/local.udhcpd.conf 2>&-)
EOM
			/usr/sbin/udhcpd
		fi
	;;
	stop)
		echo "Stopping udhcpd..."
		killall udhcpd
	;;
	restart)
		$0 stop
		$0 start
	;;
	*)
		echo "Usage: $0 start|stop|restart"
	;;
esac
