#!/lib/runit/invoke-run

readonly name=dnsmasq
readonly daemon=/usr/sbin/dnsmasq
readonly marker=/usr/share/dnsmasq/installed-marker

test -e "${marker}" || exec sv down "${name}"
test -x "${daemon}" || exec sv down "${name}"

if [ ! "${RESOLV_CONF:-}" ] &&
   [ "${IGNORE_RESOLVCONF:-}" != "yes" ] &&
   [ -x /sbin/resolvconf ]
then
	RESOLV_CONF=/run/dnsmasq/resolv.conf
fi

# This tells dnsmasq to ignore DNS requests that don't come from a local network.
# It's automatically ignored if  --interface --except-interface, --listen-address 
# or --auth-server exist in the configuration, so for most installations, it will
# have no effect, but for otherwise-unconfigured installations, it stops dnsmasq
# from being vulnerable to DNS-reflection attacks.

DNSMASQ_OPTS="${DNSMASQ_OPTS:-} --local-service"

# If the dns-root-data package is installed, then the trust anchors will be 
# available in $ROOT_DS, in BIND zone-file format. Reformat as dnsmasq
# --trust-anchor options.

ROOT_DS="/usr/share/dns/root.ds"

if [ -f $ROOT_DS ]; then
    DNSMASQ_OPTS="$DNSMASQ_OPTS `env LC_ALL=C sed -rne "s/^([.a-zA-Z0-9]+)([[:space:]]+[0-9]+)*([[:space:]]+IN)*[[:space:]]+DS[[:space:]]+/--trust-anchor=\1,/;s/[[:space:]]+/,/gp" $ROOT_DS | tr '\n' ' '`"
fi

mkdir -p /run/dnsmasq
chown dnsmasq:nogroup /run/dnsmasq
[ -x /sbin/restorecon ] && /sbin/restorecon /run/dnsmasq
exec "${daemon}" \
	--keep-in-foreground \
	--log-facility=/dev/stdout \
	${RESOLV_CONF:+ -r $RESOLV_CONF} \
	${DNSMASQ_OPTS} \
	-u dnsmasq
