#!/bin/sh
# 
# dnsmasq

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/dnsmasq
NAME="dnsmasq"
DESC="caching dns forwarder"

# Most configuration options in /etc/default/dnsmasq are deprecated
# but still honoured.

if [ -f /etc/default/$NAME ]; then
	. /etc/default/$NAME
fi

test -f $DAEMON || exit 0

# If the resolvconf package is installed then use the resolv conf file
# that it provides as the default.  (Otherwise use /etc/resolv.conf as
# the default.)
#
# This setting can be overridden by setting the RESOLV_CONF environment
# variable in /etc/default/dnsmasq or by including a resolv-file
# line in /etc/dnsmasq.conf .

if [ ! "$RESOLV_CONF" ] &&
   [ -x /sbin/resolvconf ]
then
	RESOLV_CONF=/var/run/dnsmasq/resolv.conf
fi

for INTERFACE in $DNSMASQ_INTERFACE; do
	DNSMASQ_INTERFACES="$DNSMASQ_INTERFACES -i $INTERFACE"
done

set -e

start()
{
	start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
		--exec $DAEMON -- \
		${MAILHOSTNAME:+ -m $MAILHOSTNAME} \
		${MAILTARGET:+ -t $MAILTARGET} \
		${DNSMASQ_USER:+ -u $DNSMASQ_USER} \
		${DNSMASQ_INTERFACE:+ $DNSMASQ_INTERFACES} \
		${DHCP_LEASE:+ -l $DHCP_LEASE} \
		${DOMAIN_SUFFIX:+ -s $DOMAIN_SUFFIX} \
		${RESOLV_CONF:+ -r $RESOLV_CONF} \
		${CACHESIZE:+ -c $CACHESIZE} \
		${DNSMASQ_OPTS:+ $DNSMASQ_OPTS}
	[ "$?" = 0 ] && { [ ! -x /sbin/resolvconf ] || echo "nameserver 127.0.0.1" | /sbin/resolvconf -a lo ; }
}

stop()
{
	[ ! -x /sbin/resolvconf ] || /sbin/resolvconf -d lo
	start-stop-daemon -o --stop --quiet --pidfile /var/run/$NAME.pid \
		--exec $DAEMON
}

reload()
{
	start-stop-daemon --stop --signal HUP --quiet \
		--pidfile /var/run/$NAME.pid --exec $DAEMON
}

case "$1" in
    start)
	echo -n "Starting $DESC: "
	start
	echo "$NAME."
	;;
    stop)
	echo -n "Stopping $DESC: "
	stop
	echo "$NAME."
	;;
    reload|force-reload)
	echo -n "Reloading $DESC information"
	reload
	echo "."
	;;
    restart)
	echo -n "Restarting $DESC: "
	stop
	sleep 1
	start
	echo "$NAME."
	;;
    *)
	echo "Usage: /etc/init.d/$NAME {start|stop|restart|reload|force-reload}" >&2
	exit 3
	;;
esac

exit 0
