#!/bin/sh /etc/rc.common
# Copyright (C) 2007-2012 OpenWrt.org

START=24

. /lib/zone/zone_api.sh

USE_PROCD=1
PROG=/usr/sbin/dnsmasq
PROG_OMADA="vnete /usr/sbin/dnsmasq"

DNS_SERVERS=""
DOMAIN=""

ADD_LOCAL_DOMAIN=1
ADD_LOCAL_HOSTNAME=1

DF_CONFIGFILE="/var/etc/dnsmasq.conf"
DF_HOSTFILE="/tmp/hosts/dhcp"
TRUSTANCHORSFILE="/usr/share/dnsmasq/trust-anchors.conf"
DEBUG_FILE=/tmp/dhcp_debug.log

DHCP_DBG_LOG_PATH="/var/log/dhcp.log"

run_pools=""
local LOCAL_NETWORK=127.0.0.1
multilan() {
	local m=$(uci -c /etc/profile.d get profile.@global[0].multilan)
	if [ $m == 1 ]; then
		return 0
	else
		return 1
	fi
}

xappend() {
	local value="$1"
	local CONFIGFILE="$2"

	echo "${value#--}" >> $CONFIGFILE
}
dhcp_conf_add() 
{
	#echo "enter dhcp_conf_add" >/dev/console
	[ -n "$1" ] && {
		#echo "add inteface: $1"
    	lua /usr/lib/lua/dhcp_server/dhcp_load.lua $1
	}
	#echo "exit dhcp_conf_add" >/dev/console
}

dhcp_calc() {
	local ip="$1"
	local res=0

	while [ -n "$ip" ]; do
		part="${ip%%.*}"
		res="$(($res * 256))"
		res="$(($res + $part))"
		[ "${ip%.*}" != "$ip" ] && ip="${ip#*.}" || ip=
	done
	echo "$res"
}

dhcp_check() {
	local ifname="$1"
	local stamp="/var/run/dnsmasq.$ifname.dhcp"
	local rv=0

	[ -s "$stamp" ] && return $(cat "$stamp")

	udhcpc -n -q -s /bin/true -t 1 -i "$ifname" >&- && rv=1 || rv=0

	[ $rv -eq 1 ] && \
		logger -t dnsmasq \
			"found already running DHCP-server on interface '$ifname'" \
			"refusing to start, use 'option force 1' to override"

	echo $rv > "$stamp"
	return $rv
}

log_once() {
	pidof dnsmasq >/dev/null || \
		logger -t dnsmasq "$@"
}

append_bool() {
	local section="$1"
	local option="$2"
	local value="$3"
	local CONFIGFILE="$4"
	local _loctmp
	config_get_bool _loctmp "$section" "$option" 0
	[ $_loctmp -gt 0 ] && xappend "$value" $CONFIGFILE
}

append_parm() {
	local section="$1"
	local option="$2"
	local switch="$3"
	local CONFIGFILE="$4"
	local _loctmp
	config_get _loctmp "$section" "$option"
	[ -z "$_loctmp" ] && return 0
	xappend "$switch=$_loctmp" $CONFIGFILE
}

append_server() {
	xappend "--server=$1" "$DF_CONFIGFILE"
}

append_address() {
	xappend "--address=$1" "$DF_CONFIGFILE"
}

append_interface() {
	local ifname=$(uci_get_state network "$1" ifname "$1")
	xappend "--interface=$ifname" "$2"
}

append_leasefile() {
	local interface=$1
	local filepath="/tmp/dhcp.$interface.leases"
	xappend "--dhcp-leasefile=$filepath" "$2"
}

append_domain_dnsmasq() {
	local interface=$1
	xappend "--domain=$interface" "$2"
}

append_server_dnsmasq() {
	local interface=$1
	xappend "--server=/$interface/" "$2"
}

append_notinterface() {
	local ifname=$(uci_get_state network "$1" ifname "$1")
	xappend "--except-interface=$ifname" "$DF_CONFIGFILE"
}

append_addnhosts() {
	xappend "--addn-hosts=$1" "$DF_CONFIGFILE"
}

append_bogusnxdomain() {
	xappend "--bogus-nxdomain=$1" "$DF_CONFIGFILE"
}

dnsmasq() {
	local cfg="$1"
	local interface="$2"
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"
	
        #echo "CONFIGFILE=$CONFIGFILE"
        #echo "HOSTFILE=$HOSTFILE"

	append_bool "$cfg" authoritative "--dhcp-authoritative" $CONFIGFILE
	append_bool "$cfg" nodaemon "--no-daemon" $CONFIGFILE
	append_bool "$cfg" domainneeded "--domain-needed" $CONFIGFILE
	append_bool "$cfg" filterwin2k "--filterwin2k" $CONFIGFILE
	append_bool "$cfg" nohosts "--no-hosts" $CONFIGFILE
	append_bool "$cfg" nonegcache "--no-negcache" $CONFIGFILE
	append_bool "$cfg" strictorder "--strict-order" $CONFIGFILE
	append_bool "$cfg" logqueries "--log-queries" $CONFIGFILE
	append_bool "$cfg" noresolv "--no-resolv" $CONFIGFILE
	append_bool "$cfg" localise_queries "--localise-queries" $CONFIGFILE
	append_bool "$cfg" readethers "--read-ethers" $CONFIGFILE
	append_bool "$cfg" dbus "--enable-dbus" $CONFIGFILE
	append_bool "$cfg" boguspriv "--bogus-priv" $CONFIGFILE
	append_bool "$cfg" expandhosts "--expand-hosts" $CONFIGFILE
	append_bool "$cfg" enable_tftp "--enable-tftp" $CONFIGFILE
	append_bool "$cfg" nonwildcard "--bind-interfaces" $CONFIGFILE
	append_bool "$cfg" fqdn "--dhcp-fqdn" $CONFIGFILE
	append_bool "$cfg" proxydnssec "--proxy-dnssec" $CONFIGFILE
	append_parm "$cfg" dhcpscript "--dhcp-script" $CONFIGFILE
	append_parm "$cfg" cachesize "--cache-size" $CONFIGFILE
	append_parm "$cfg" dnsforwardmax "--dns-forward-max" $CONFIGFILE
	append_parm "$cfg" port "--port" $CONFIGFILE
	append_parm "$cfg" ednspacket_max "--edns-packet-max" $CONFIGFILE
	append_parm "$cfg" dhcpleasemax "--dhcp-lease-max" $CONFIGFILE
	append_parm "$cfg" "queryport" "--query-port" $CONFIGFILE
	#append_parm "$cfg" "domain" "--domain" $CONFIGFILE
	#append_parm "$cfg" "local" "--server" $CONFIGFILE
	append_domain_dnsmasq $interface $CONFIGFILE
	append_server_dnsmasq $interface $CONFIGFILE
	config_list_foreach "$cfg" "server" append_server 
	config_list_foreach "$cfg" "address" append_address
	#config_list_foreach "$cfg" "interface" append_interface
	if (!(multilan)); then
		append_interface $interface $CONFIGFILE
	fi
	config_list_foreach "$cfg" "notinterface" append_notinterface
	config_list_foreach "$cfg" "addnhosts" append_addnhosts
	config_list_foreach "$cfg" "bogusnxdomain" append_bogusnxdomain
	#append_parm "$cfg" "leasefile" "--dhcp-leasefile" $CONFIGFILE
	append_leasefile $interface $CONFIGFILE
	append_parm "$cfg" "resolvfile" "--resolv-file" $CONFIGFILE
	append_parm "$cfg" "tftp_root" "--tftp-root" $CONFIGFILE
	append_parm "$cfg" "dhcp_boot" "--dhcp-boot" $CONFIGFILE
	append_parm "$cfg" "local_ttl" "--local-ttl" $CONFIGFILE

	config_get DOMAIN "$cfg" domain
	config_get_bool ADD_LOCAL_DOMAIN "$cfg" add_local_domain 1
	config_get_bool ADD_LOCAL_HOSTNAME "$cfg" add_local_hostname 1

	config_get_bool readethers "$cfg" readethers
	[ "$readethers" = "1" -a \! -e "/etc/ethers" ] && touch /etc/ethers

	#config_get leasefile $cfg leasefile
	#[ -n "$leasefile" -a \! -e "$leasefile" ] && touch "$leasefile"
	touch "/tmp/dhcp.$interface.leases"
	config_get_bool cachelocal "$cfg" cachelocal 1
	config_get hostsfile "$cfg" dhcphostsfile
	[ -e "$hostsfile" ] && xappend "--dhcp-hostsfile=$hostsfile" $CONFIGFILE

	mkdir -p /tmp/hosts /tmp/dnsmasq.d
	xappend "--addn-hosts=/tmp/hosts" $CONFIGFILE
	xappend "--conf-dir=/tmp/dnsmasq.d" $CONFIGFILE
	local rebind
	config_get_bool rebind "$cfg" rebind_protection 1
	[ $rebind -gt 0 ] && {
		log_once \
			"DNS rebinding protection is active," \
			"will discard upstream RFC1918 responses!"
		xappend "--stop-dns-rebind" $CONFIGFILE

		local rebind_localhost
		config_get_bool rebind_localhost "$cfg" rebind_localhost 0
		[ $rebind_localhost -gt 0 ] && {
			log_once "Allowing 127.0.0.0/8 responses"
			xappend "--rebind-localhost-ok" $CONFIGFILE
		}

		append_rebind_domain() {
			log_once "Allowing RFC1918 responses for domain $1"
			xappend "--rebind-domain-ok=$1" $CONFIGFILE
		}

		config_list_foreach "$cfg" rebind_domain append_rebind_domain
	}
        
	config_get_bool dnssec "$cfg" dnssec 0
	[ "$dnssec" -gt 0 ] && {
		xappend "--conf-file=$TRUSTANCHORSFILE" $CONFIGFILE
		xappend "--dnssec" $CONFIGFILE
		append_bool "$cfg" dnsseccheckunsigned "--dnssec-check-unsigned" $CONFIGFILE
	}

	dhcp_option_add "$cfg" "" $CONFIGFILE 0 

	xappend "--dhcp-broadcast=tag:needs-broadcast" $CONFIGFILE
	echo >> $CONFIGFILE
}

dhcp_subscrid_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get subscriberid "$cfg" subscriberid
	[ -n "$subscriberid" ] || return 0

	xappend "--dhcp-subscrid=$networkid,$subscriberid" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" $force" 
}

dhcp_remoteid_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get remoteid "$cfg" remoteid
	[ -n "$remoteid" ] || return 0

	xappend "--dhcp-remoteid=$networkid,$remoteid" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force"
}

dhcp_circuitid_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get circuitid "$cfg" circuitid
	[ -n "$circuitid" ] || return 0

	xappend "--dhcp-circuitid=$networkid,$circuitid" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force"
}

dhcp_userclass_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get userclass "$cfg" userclass
	[ -n "$userclass" ] || return 0

	xappend "--dhcp-userclass=$networkid,$userclass" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force" 
}

dhcp_vendorclass_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get vendorclass "$cfg" vendorclass
	[ -n "$vendorclass" ] || return 0

	xappend "--dhcp-vendorclass=$networkid,$vendorclass" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force"
}


dhcp_tag_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	tag="$cfg"

	[ -n "$tag" ] || return 0

	config_get_bool force "$cfg" force 0
	[ "$force" = "0" ] && force=

	config_get option "$cfg" dhcp_option
	for o in $option; do
		xappend "--dhcp-option${force:+-force}=tag:$tag,$o" $CONFIGFILE
	done
}

dhcp_mac_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] || return 0

	config_get mac "$cfg" mac
	[ -n "$mac" ] || return 0

	xappend "--dhcp-mac=$networkid,$mac" $CONFIGFILE

	dhcp_option_add "$cfg" "$networkid" $CONFIGFILE
}

dhcp_boot_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if $cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get networkid "$cfg" networkid

	config_get filename "$cfg" filename
	[ -n "$filename" ] || return 0

	config_get servername "$cfg" servername
	[ -n "$servername" ] || return 0

	config_get serveraddress "$cfg" serveraddress
	[ -n "$serveraddress" ] || return 0

	xappend "--dhcp-boot=${networkid:+net:$networkid,}$filename,$servername,$serveraddress" $CONFIGFILE

	config_get_bool force "$cfg" force 0

	dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force"
}

ippool_exist()
{
	local pools
	local pool

	ippool-control -l
	pools=$(grep 'poolname:@dhcp.' /tmp/ippoold.txt | sed -E 's/^poolname:(@dhcp.[^ ]*).*$/\1/g')
	for pool in $pools
	do
		[ "$pool" = "$1" ] && {
			return 0
		}
	done
	return 1
}

dhcp_add() {
	local cfg="$1"
	config_get net "$cfg" interface
	[ -n "$net" ] || {
		echo "net" >> $DEBUG_FILE
	}

	local CONFIGFILE="/var/etc/dnsmasq.$net.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$net"
	
	config_get dhcpv4 "$cfg" dhcpv4
	#[ "$dhcpv4" != "disabled" ] || {
	#    echo "dhcpv4 disabled" >> $DEBUG_FILE
	#	return 0
	#}

	config_get networkid "$cfg" ifname
	[ -n "$networkid" ] || networkid="$net"

	#network_get_subnet subnet "$net" || return 0
	if (!(multilan)); then
		network_get_subnet subnet "$net"
		 [ -z $subnet ] && {
			echo "subnet" >> $DEBUG_FILE
			return 0
		 }
		
		#network_get_device ifname "$net" || return 0
		network_get_device ifname "$net"
		[ -z $ifname ] && {
			echo "ifname" >> $DEBUG_FILE
			return 0
		}
		
		#network_get_protocol proto "$net" || return 0
		network_get_protocol proto "$net"
		[ -z $proto ] && {
			echo "proto" >> $DEBUG_FILE
			return 0
		}
	fi

	[ "$cachelocal" = "0" ] && network_get_dnsserver dnsserver "$net" && {
		DNS_SERVERS="$DNS_SERVERS $dnsserver"
	}

	append_bool "$cfg" ignore "--no-dhcp-interface=$ifname" $CONFIGFILE && return 0

	# Do not support non-static interfaces for now
	if (multilan); then
		proto="static"
	fi
	[ static = "$proto" ] || {
		echo "static proto" >> $DEBUG_FILE
		return 0
	}

	# Override interface netmask with dhcp config if applicable
	if (!(multilan)); then
		config_get netmask "$cfg" netmask "${subnet##*/}"
	else
		config_get netmask "$cfg" netmask "255.255.255.0"
	fi

	#check for an already active dhcp server on the interface, unless 'force' is set
	#config_get_bool force "$cfg" force 0
	#[ $force -gt 0 ] || dhcp_check "$ifname" || {
	#	echo "dhcp_check" >> $DEBUG_FILE
	#	return 0
	#}

	if (!(multilan)); then
		config_get start "$cfg" start
		config_get limit "$cfg" limit
		config_get leasetime "$cfg" leasetime
	else
		config_get dhcp_start "$cfg" dhcp_start
		config_get dhcp_end "$cfg" dhcp_end
		config_get dhcp_release_time "$cfg" dhcp_release_time
	fi
	config_get options "$cfg" options
	config_get_bool dynamicdhcp "$cfg" dynamicdhcp 1
	local addrtype_v2
	config_get addrtype_v2 "$cfg" addrtype_v2

	if (!(multilan)); then
		leasetime="${leasetime:-120m}"
		start="$(dhcp_calc "${start:-100}")"
		limit="${limit:-150}"
		[ "$limit" -gt 0 ] && limit=$((limit-1))
		eval "$(ipcalc.sh "${subnet%%/*}" $netmask $start $limit)"
	else
		dhcp_release_time="${dhcp_release_time:-120m}"
	fi
	if [ "$dynamicdhcp" = "0" ]; then END="static"; fi
	echo "pool set" >> $DEBUG_FILE
	if [ "$addrtype_v2" == "iprange" ];then
		echo "iprange" >> $DEBUG_FILE
		if (!(multilan)); then
			xappend "--dhcp-range=$networkid,$START,$END,$NETMASK,$leasetime${options:+ $options}" $CONFIGFILE
		else
			xappend "--interface=$networkid" $CONFIGFILE
			xappend "--dhcp-range=$networkid,$dhcp_start,$dhcp_end,$netmask,$dhcp_release_time${options:+ $options}" $CONFIGFILE
		fi
	elif (!(multilan)); then
		local ippool
		config_get ippool "$cfg" ippool

		cat /tmp/etc/ippool.conf |while read line
		
		echo "ippool" >> $DEBUG_FILE
		do
			name=`echo $line | cut -d "#" -f 1`
			if [ "$name" == "$ippool" ]; then
				START=`echo $line | cut -d "#" -f 2`
				END=`echo $line | cut -d "#" -f 3`
                		xappend "--dhcp-ippoolname=$networkid,$ippool,$START,$END,$NETMASK,$leasetime${options:+ $options}" $CONFIGFILE
			fi
		done		
	else
		xappend "--interface=$networkid" $CONFIGFILE
		xappend "--dhcp-ippoolname=$networkid,"@dhcp.$networkid",$dhcp_start,$dhcp_end,$netmask,$dhcp_release_time${options:+ $options}" $CONFIGFILE
		if $(ippool_exist "@dhcp.$networkid"); then
			ippool-control -m -n "@dhcp.$networkid" -b $dhcp_start -e $dhcp_end
		else
			ippool-control -a -n "@dhcp.$networkid" -b $dhcp_start -e $dhcp_end -u
		fi
		run_pools="${run_pools} @dhcp.$networkid"
	fi

	dhcp_option_add "$cfg" "$networkid" $CONFIGFILE
}

dhcp_relay_add() {
	local cfg="$1"
	
	config_get dhcp_relay_on "$cfg" dhcp_relay_on
	if [ -n "$dhcp_relay_on" ];then
		if [ "$dhcp_relay_on" == "1" ];then
			config_get dhcp_relay_server "$cfg" dhcp_relay_server
			if [ -n "$dhcp_relay_server" ];then
				config_get zone "$cfg" zone
				if [ -n "$zone" ];then
					if_eth=$(uci_get zone "$zone" if_eth)
					if_ipaddr=$(uci_get vnetwork "$if_eth" ipaddr)
					xappend "--dhcp-relay=$if_ipaddr,$dhcp_relay_server" $CONFIGFILE
				fi
			fi
		fi
	fi
}

dhcp_option_append() {
	local opt="${1//\"/\"\\\"\"}"
	xappend "$2${opt}" $CONFIGFILE
}

dhcp_option_add() {
	local cfg="$1"
	local networkid="$2"
	local CONFIGFILE="$3"
	local force="$4"

	[ "$force" = "0" ] && force=

	config_list_foreach "$cfg" dhcp_option dhcp_option_append \
		"--dhcp-option${force:+-force}=${networkid:+$networkid,}"
}

dhcp_domain_add() {
	local cfg="$1"
	local ip name names record
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get names "$cfg" name "$3"
	[ -n "$names" ] || return 0

	config_get ip "$cfg" ip "$3"
	[ -n "$ip" ] || return 0

	for name in $names; do
		record="${record:+$record }$name"
	done

	echo "$ip $record" >> $HOSTFILE
}

dhcp_srv_add() {
	local cfg="$1"
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get srv "$cfg" srv
	[ -n "$srv" ] || return 0

	config_get target "$cfg" target
	[ -n "$target" ] || return 0

	config_get port "$cfg" port
	[ -n "$port" ] || return 0

	config_get class "$cfg" class
	config_get weight "$cfg" weight

	local service="$srv,$target,$port${class:+,$class${weight:+,$weight}}"

	xappend "--srv-host=$service" $CONFIGFILE
}

dhcp_mx_add() {
	local cfg="$1"
	local domain relay pref
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get domain "$cfg" domain
	[ -n "$domain" ] || return 0

	config_get relay "$cfg" relay
	[ -n "$relay" ] || return 0

	config_get pref "$cfg" pref 0

	local service="$domain,$relay,$pref"

	xappend "--mx-host=$service" $CONFIGFILE
}

dhcp_cname_add() {
	local cfg="$1"
	local cname target
	local interface="$2"
	local if
	
	config_get if "$cfg" interface
	if [ "$if" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

	config_get cname "$cfg" cname
	[ -n "$cname" ] || return 0

	config_get target "$cfg" target
	[ -n "$target" ] || return 0

	xappend "--cname=${cname},${target}" $CONFIGFILE
}

dhcp_hostrecord_add() {
	local cfg="$1"
	local names addresses record val

	config_get names "$cfg" name "$2"
	if [ -z "$names" ]; then
		return 0
	fi

	config_get addresses "$cfg" ip "$3"
	if [ -z "$addresses" ]; then
		return 0
	fi

	for val in $names $addresses; do
		record="${record:+$record,}$val"
	done

	xappend "--host-record=$record"
}

service_triggers()
{
	procd_add_reload_trigger "dhcp"
}

boot() {
	# Will be launched through hotplug
	# if dhcp pool not exist in ippool, restart dnsmasq
	local pools
	ippool-control -l
	pools=$(grep 'poolname:@dhcp.' /tmp/ippoold.txt | sed -E 's/^poolname:(@dhcp.[^ ]*).*$/\1/g')
	if [ -z "$pools" ]; then
		stop
		start
	fi
	return 0
}

dhcp_host_service() {
    local cfg="$1"
	local interface="$2"
	local ifname
	
	config_get ifname "$cfg" interface
	local iface=$(zone_get_effect_ifaces $ifname)
	if [ "$iface" != "$interface" ]; then
	    return 0
	fi
	
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	local HOSTFILE="/tmp/hosts/dhcp.$interface"

    #echo "host:CONFIGFILE=$CONFIGFILE"

	config_get_bool force "$cfg" force 0
	
	config_get enable "$cfg" enable
        [ "$enable" = "on" ] || return 0 

	config_get networkid "$cfg" networkid
	[ -n "$networkid" ] && dhcp_option_add "$cfg" "$networkid" "$CONFIGFILE" "$force"

	#config_get name "$cfg" name
	config_get ip "$cfg" ip
	[ -n "$ip" -o -n "$name" ] || return 0

	config_get_bool dns "$cfg" dns 0
	[ "$dns" = "1" -a -n "$ip" -a -n "$name" ] && {
		echo "$ip $name${DOMAIN:+.$DOMAIN}" >> $HOSTFILE
	}

	config_get mac "$cfg" mac
	if [ -n "$mac" ]; then
		# --dhcp-host=00:20:e0:3b:13:af,192.168.0.199,lap
		macs=""
		for m in $mac; do append macs "$m" ","; done
	else
		# --dhcp-host=lap,192.168.0.199
		[ -n "$name" ] || return 0
		macs="$name"
		name=""
	fi

	config_get tag "$cfg" tag

	config_get_bool broadcast "$cfg" broadcast 0
	[ "$broadcast" = "0" ] && broadcast=

	xappend "--dhcp-host=$macs${networkid:+,net:$networkid}${broadcast:+,set:needs-broadcast}${tag:+,set:$tag}${ip:+,$ip}${name:+,$name}" $CONFIGFILE
}

start_service() {
	if (!(multilan)); then
		include /lib/functions
		config_load dhcp
		config_foreach service_daemon dhcp
	else
		service_daemon
	fi
}

flush_unused_dhcp_ippool()
{
	local pools=""
	local pool

	ippool-control -l
	pools=$(grep 'poolname:@dhcp.' /tmp/ippoold.txt | sed -E 's/^poolname:(@dhcp.[^ ]*).*$/\1/g')
	for pool in $pools
	do
		pool_find=""
		for run_pool in $run_pools
		do
			[ "$pool" = "$run_pool" ] && pool_find="yes"
		done
		[ -z "$pool_find" ] && {
			ippool-control -d -n $pool
		}
	done
}

service_daemon() {
	include /lib/functions
	
	# if (!(multilan)); then
	# 	local dhcp_cfg="$1"
	# 	local interface
	# else
		config_load dhcp
		local interface="lan" 
	# fi
	local CONFIGFILE
	#local HOSTFILE
	
	# echo "service_daemon" >> $DEBUG_FILE
	# if (!(multilan)); then
	# 	interface=$(uci_get dhcp "$dhcp_cfg" interface)
	# fi
    # echo "interface=$interface" >> $DEBUG_FILE
	local CONFIGFILE="/var/etc/dnsmasq.$interface.conf"
	#local HOSTFILE="/tmp/hosts/dhcp.$interface"
    # echo "CONFIGFILE=$CONFIGFILE" >> $DEBUG_FILE
    # echo "HOSTFILE=$HOSTFILE" >> $DEBUG_FILE
	
	procd_open_instance
	# if (!(multilan)); then
	# 	procd_set_param command $PROG -C $CONFIGFILE -k
	# else
		procd_set_param command $PROG_OMADA -C $CONFIGFILE -k --log-dhcp --log-async --log-facility=$DHCP_DBG_LOG_PATH
	# fi
	procd_set_param file $CONFIGFILE
	procd_set_param respawn
	procd_close_instance
        
	# before we can call xappend
	mkdir -p $(dirname $CONFIGFILE)

	echo "# auto-generated config file from /etc/config/dhcp" > $CONFIGFILE
	#echo "# auto-generated config file from /etc/config/dhcp" > $HOSTFILE
	echo "user=root" >> $CONFIGFILE
	# if we did this last, we could override auto-generated config
	[ -f /etc/dnsmasq.conf ] && {
		xappend "--conf-file=/etc/dnsmasq.conf" $CONFIGFILE
	}

	args=""
	# config_foreach dnsmasq dnsmasq $interface 
	
	#config_foreach dhcp_host_service host $interface
	#echo "excuting dhcp_host_add" > /dev/console
	dhcp_conf_add $interface

	# echo >> $CONFIGFILE
	# config_foreach dhcp_boot_add boot $interface 
	# config_foreach dhcp_mac_add mac $interface 
	# config_foreach dhcp_tag_add tag $interface 
	# config_foreach dhcp_vendorclass_add vendorclass $interface 
	# config_foreach dhcp_userclass_add userclass $interface 
	# config_foreach dhcp_circuitid_add circuitid $interface 
	# config_foreach dhcp_remoteid_add remoteid $interface 
	# config_foreach dhcp_subscrid_add subscrid $interface 
	# config_foreach dhcp_domain_add domain $interface 
	# config_foreach dhcp_hostrecord_add hostrecord $interface 

	# add own hostname
	# local lanaddr
	# [ $ADD_LOCAL_HOSTNAME -eq 1 ] && network_get_ipaddr lanaddr "lan" && {
	# 	local hostname="$(uci_get system @system[0] hostname OpenWrt)"
	# 	dhcp_domain_add "" "$hostname" $interface "$lanaddr"
	# }

	# echo >> $CONFIGFILE
	# config_foreach dhcp_srv_add srvhost $interface 
	# config_foreach dhcp_mx_add mxhost $interface 
	# echo >> $CONFIGFILE
        
	# config_get odhcpd_is_active odhcpd maindhcp
	# if [ "$odhcpd_is_active" != "1" ]; then
	# 	if (!(multilan)); then
	# 		dhcp_add $dhcp_cfg
	# 	else
	# 		config_foreach dhcp_relay_add vinterface
	# 		config_foreach dhcp_add vinterface
	# 	fi
	# 	flush_unused_dhcp_ippool
	# fi

	# echo >> $CONFIGFILE
	# config_foreach dhcp_cname_add cname $interface 
	# echo >> $CONFIGFILE

	# rm -f /tmp/resolv.conf
	# touch /tmp/resolv.conf
	# [ -f /tmp/resolv.conf ] && {
	# 	rm -f /tmp/resolv.conf
	# 	ln -s /tmp/resolv.conf.auto /tmp/resolv.conf
	# }
	
	# echo "dhcp start end" >> $DEBUG_FILE
	#[ $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
	#开机启动添加127.0.0.1到resolv.conf
	local_dns=`cat /tmp/resolv.conf | grep -w "${LOCAL_NETWORK}"`
	[ -z "${local_dns}" ] && {
		echo "nameserver ${LOCAL_NETWORK}" >> /tmp/resolv.conf
	}
}

_stop_service_clear() {
	local cfg=$1
	local ignore
	local interface
	
	config_get ignore "$cfg" ignore
	if [ "$ignore" == "1" ]; then
        config_get interface "$cfg" interface
		rm -rf /tmp/dhcp.$interface.leases
	fi
}

stop_service_clear() {
    config_load dhcp
	if (!(multilan)); then
		config_foreach _stop_service_clear dhcp
	else
		config_foreach _stop_service_clear vinterface
	fi
}

reload_service() {
   # stop_service_clear
	rc_procd start_service "$@"
	return 0
}

stop_service() {
	return 0
	# [ -f /tmp/resolv.conf ] && {
	# 	rm -f /tmp/resolv.conf
	# 	ln -s /tmp/resolv.conf.auto /tmp/resolv.conf
	# }
	# rm -f /var/run/dnsmasq.*.dhcp
	# #rm -rf /tmp/dhcp.*.leases
}
