#!/bin/sh /etc/rc.common
# Copyright (C) 2007-2012 OpenWrt.org
# patch by yinjiajin@xiaomi.com, use conf-dir

START=48
STOP=60 # stop dnsmasq to ensure it will not miss up LAN

SERVICE_USE_PID=1

DNS_SERVERS=""
DOMAIN=""

ADD_LOCAL_DOMAIN=1
ADD_LOCAL_HOSTNAME=1

CONFIGFILE="/var/etc/dnsmasq.conf"

EXECMD="/usr/sbin/dnsmasq --user=root -C ${CONFIGFILE}"
export OOM_FLAG=0

. /lib/dnsmasq/gen_config_from_uci

start() {
	local LOCKFILE=/var/lock/dnsmasq_init.lock
	trap "lock -u ${LOCKFILE}; return 0" EXIT HUP INT QUIT PIPE TERM
	lock $LOCKFILE
	include /lib/network
	scan_interfaces

	local lanipaddr
	config_load network
        config_get lanipaddr lan ipaddr '192.168.31.1'

	config_load dhcp

	# before we can call xappend
	mkdir -p $(dirname $CONFIGFILE)

	echo "# auto-generated config file from /etc/config/dhcp" > $CONFIGFILE
	mkdir -p /etc/dnsmasq.d/
	if [ $? -ne 0 ]
		then
		conlog "ERROR: mkdir -p /etc/dnsmasq.d/ failed."
		exit 1
	fi
	[ -d /tmp/etc ] || mkdir -p /tmp/etc/
	cp -a /etc/dnsmasq.d /tmp/etc/ 2>/dev/null && logger -t dnsmasq "sync /etc/dnsmasq.d to /tmp/etc/"
	if [ $? -ne 0 ]
		then
		logger -t dnsmasq "INFO: --config-dir=/etc/dnsmasq.d/"
		xappend "--conf-dir=/etc/dnsmasq.d/"
	else
		logger -t dnsmasq "INFO: --config-dir=/tmp/etc/dnsmasq.d/"
		xappend "--conf-dir=/tmp/etc/dnsmasq.d/"
	fi
	#disabled legacy config file /etc/dnsmasq.conf
	needclean=$(cat /etc/dnsmasq.conf 2>/dev/null | grep -v '^#' | grep -cv '^$')
	if [ $needclean -ne 0 ]
		then
		logger -t dnsmasq "WARNING: diable legacy config /etc/dnsmasq.conf, backup to /etc/dnsmasq.conf.disabled.$$"
		cat /etc/dnsmasq.conf > /etc/dnsmasq.conf.disabled.$$
		rm -f /overlay/etc/dnsmasq.conf
	fi
	#
	#log ignored noexist link file
	filelist=`ls /etc/dnsmasq.d/`
	for onefile in $filelist
	do
		if [ ! -f "/etc/dnsmasq.d/$onefile" ]
			then
			#it is ignored by dnsmasq code
			#rm -f "/etc/dnsmasq.d/$onefile"
			logger -t dnsmasq "no-exist file, ignored: /etc/dnsmasq.d/$onefile"
		fi
	done
	#
	#a flag for dnsmasq status detecting
	#address=/workforme.stat.localdomain/127.0.0.1
	xappend "--address=/workforme.stat.localdomain/127.0.0.1"
	#
	#setup router domain

	#
	#xappend "--address=/miwifi.com/$lanipaddr"
	#
	mkdir -p /tmp/hosts/ && echo "${lanipaddr} miwifi.com" > /tmp/hosts/miwifi.com && \
	echo "${lanipaddr} www.miwifi.com" > /tmp/hosts/www.miwifi.com
	if [ $? -ne 0 ]
		then
		logger -t dnsmasq "ERROR: save ${lanipaddr} miwifi.com to /tmp/hosts/miwifi.com failed."
	fi
	myhostname="$(uci get system.@system[0].hostname 2>/dev/null)"
	if [ -z "$myhostname" ]
		then
		logger -t dnsmasq "ERROR: hostname no found: $(uci get system.@system[0].hostname 2>&1)"
	else
		mkdir -p /tmp/hosts/ && echo "${lanipaddr} ${myhostname}" > /tmp/hosts/${myhostname}
		if [ $? -ne 0 ]
			then
			#domainneeded
			logger -t dnsmasq "ERROR: save ${lanipaddr} ${myhostname} to /tmp/hosts/${myhostname} failed."
		fi
	fi
	mydomain="$(uci get dhcp.@dnsmasq[0].domain 2>/dev/null)"
	test -z "$mydomain" && mydomain='lan'
	if [ -n "$mydomain" -a -n "$myhostname" ]
		then
		staticfqdn="${myhostname}.${mydomain}"
		mkdir -p /tmp/hosts/ && echo "${lanipaddr} ${staticfqdn}" > /tmp/hosts/${staticfqdn}
		if [ $? -ne 0 ]
			then
			#domainneeded
			logger -t dnsmasq "ERROR: save ${lanipaddr} ${staticfqdn} to /tmp/hosts/${staticfqdn} failed."
		fi
		staticfqdn="miwifi.com.${mydomain}"
		mkdir -p /tmp/hosts/ && echo "${lanipaddr} ${staticfqdn}" > /tmp/hosts/${staticfqdn}
		if [ $? -ne 0 ]
			then
			#domainneeded
			logger -t dnsmasq "ERROR: save ${lanipaddr} ${staticfqdn} to /tmp/hosts/${staticfqdn} failed."
		fi
		staticfqdn="www.miwifi.com.${mydomain}"
		mkdir -p /tmp/hosts/ && echo "${lanipaddr} ${staticfqdn}" > /tmp/hosts/${staticfqdn}
		if [ $? -ne 0 ]
			then
			#domainneeded
			logger -t dnsmasq "ERROR: save ${lanipaddr} ${staticfqdn} to /tmp/hosts/${staticfqdn} failed."
		fi
	fi

	#clear cache onreload, set in /etc/config/dhcp
	#xappend "--clear-on-reload"

	args=""
	config_foreach dnsmasq dnsmasq
	config_foreach dhcp_host_add host
	echo >> $CONFIGFILE
	config_foreach dhcp_boot_add boot
	config_foreach dhcp_mac_add mac
	config_foreach dhcp_tag_add tag
	config_foreach dhcp_vendorclass_add vendorclass
	config_foreach dhcp_userclass_add userclass
	config_foreach dhcp_circuitid_add circuitid
	config_foreach dhcp_remoteid_add remoteid
	config_foreach dhcp_subscrid_add subscrid
	config_foreach dhcp_domain_add domain
	echo >> $CONFIGFILE
	config_foreach dhcp_srv_add srvhost
	config_foreach dhcp_mx_add mxhost
	echo >> $CONFIGFILE
	config_foreach dhcp_add dhcp
	echo >> $CONFIGFILE
	config_foreach dhcp_cname_add cname
	echo >> $CONFIGFILE

	# add own hostname
	[ $ADD_LOCAL_HOSTNAME -eq 1 ] && [ -n "$lanipaddr" ] && {
		local hostname="$(uci_get system.@system[0].hostname)"
		dhcp_domain_add "" "${hostname:-OpenWrt}" "$lanipaddr"
	}
	remote_resolv=0
	DEVINITMARK="$(uci get xiaoqiang.common.INITTED 2>/dev/null)"
	if [ "${DEVINITMARK}" != 'YES' ]
		then
		remote_resolv=1
		# ${lanipaddr}
		logger -t dnsmasq "WARNING: "
		logger -t dnsmasq "WARNING: all domain resolv to ${lanipaddr} for router has not initialed."
		logger -t dnsmasq "WARNING: "
		xappend "--address=/#/${lanipaddr}"
		#max-ttl=30
		sed -i -e '/max-ttl=/d' $CONFIGFILE && echo 'max-ttl=0' >> $CONFIGFILE
		if [ $? -ne 0 ]
			then
			logger -t dnsmasq "WARNING: set max-ttl=5 failed."
		fi
		#resolv-file=
		echo '#dummy resolv file for device no initialed' > /tmp/resolv.conf.dummy && sed -i -e '/resolv-file=/d' $CONFIGFILE && echo 'resolv-file=/tmp/resolv.conf.dummy' >> $CONFIGFILE
		if [ $? -ne 0 ]
			then
			logger -t dnsmasq "WARNING: resolv-file=/tmp/resolv.conf.dummy failed."
		fi
	fi

    #here need check if ipv6 feature is ON or OFF
    local ipv6flag=`uci get -q ipv6.settings.enabled`
    [ "$ipv6flag" != "1" ] || {
        #support ipv6 address assign with dnsmasq.
        #here must notice that prefix must equal to 64
        xappend "--enable-ra"
        xappend "--dhcp-range=::,constructor:*,ra-stateless,64"
    }

	#
	#ignored wan nic for pppoe
	#
	wannic=$(uci get network.wan.ifname 2>/dev/null)
	if [ -n "$wannic" ]
		then
		grep -q "no-dhcp-interface=$wannic" $CONFIGFILE
		if [ $? -ne 0 ]
			then
			xappend "--no-dhcp-interface=$wannic"
		fi
	fi
	# ensure /tmp/state can be written by nobody
	mkdir -p /tmp/state/
	chmod o+w /tmp/state/
	loader="/var/etc/dnsmasq_loader"
	# a help loader
	cat > $loader <<EOF
[ -f /usr/bin/trmd ] && /usr/bin/trmd -g
${EXECMD}
EOF
	export PROCLINE="ash $loader"
	export PROCFLAG="${EXECMD}"
	export PROCNUM='2'
	/usr/sbin/supervisord start
	if [ $? -eq 0 ]
		then
		rm -f /tmp/resolv.conf
		[ $ADD_LOCAL_DOMAIN -eq 1 ] && [ -n "$DOMAIN" ] && {
		    echo "search $DOMAIN" >> /tmp/resolv.conf
		}
		DNS_SERVERS="$DNS_SERVERS 127.0.0.1"
		for DNS_SERVER in $DNS_SERVERS ; do
		    echo "nameserver $DNS_SERVER" >> /tmp/resolv.conf
		done
	fi
	if [ -f /etc/ethers ]
	then
		logger -t dnsmasq "INFO: loading IP-MAC binding from /etc/ethers"
		cat /etc/ethers  | logger -t dnsmasq
		/usr/bin/arp -f 2>&1 | logger -t dnsmasq
		if [ $? -ne 0 ]
			then
			logger -t dnsmasq "WARNING: load IP-MAC binding from /etc/ethers failed."
		fi
	fi
	return 0
}

stop() {
    export PROCLINE="${EXECMD}"
    export PROCFLAG="${EXECMD}"
    # dnsmasq will fork itself.
    export PROCNUM='2'
    /usr/sbin/supervisord stop && {
	[ -f /tmp/resolv.conf ] && {
	    rm -f /tmp/resolv.conf
	    ln -s /tmp/resolv.conf.auto /tmp/resolv.conf
	}
    }

}
