#!/bin/sh
# Helper script for managing dnsmasq service
# WARNING: Don't run it manually!
# It should be running from init script or
# systemd .service file only!

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

# Assign default values, then load configuration file.
OPTIONS=""
ALL=255.255.255.255
DOMAIN_SUFFIX=$(dnsdomainname 2>/dev/null || hostname --domain 2>/dev/null)
SourceIfExists /etc/sysconfig/dnsmasq

# External commands
RESOLVCONF=/sbin/resolvconf
RESOLVCONF_LOCK=/var/run/resolvconf/lock

#---------------------------------------------------------------
#
#	/etc/resolv.conf
#

start_resolvconf()
{
	# Don't run resolvconf if we are called from resolovconf subscriber:
	# this will result in a deadlock.
	if [ -e "$RESOLVCONF_LOCK" ]; then
		return 0
	fi
	is_yes "$AUTO_LOCAL_RESOLVER" &&  [ -x "$RESOLVCONF" ] || return 0

	local msg="Setup resolv.conf for local resolver:"
	echo -n "$msg"
	echo 'nameserver 127.0.0.1' | "$RESOLVCONF" -a lo.dnsmasq &&
		success "$msg" || failure "$msg"
	echo
}

stop_resolvconf()
{
	# Don't run resolvconf if we are called from resolovconf subscriber:
	# this will result in a deadlock.
	if [ -e "$RESOLVCONF_LOCK" ]; then
		return 0
	fi
	[ -x "$RESOLVCONF" ] && "$RESOLVCONF" -i lo.dnsmasq >/dev/null 2>&1 || return 0
	action "Restore resolv.conf:" "$RESOLVCONF" -fd lo.dnsmasq
}

#---------------------------------------------------------------
#
#	Broadcast routing
#

do_route() {
	[ -n "$ALL_DEV" ] || return 0
	local msg='Broadcast device ALL_DEV is defined, but destaddr ALL is empty!'
	if [ -z "$ALL" ]; then
		echo -n $msg
		failure "$msg"; echo
		return 1
	fi
	local cmd=$1
	shift
	echo -n $*
	start_daemon --no-announce -- \
		/sbin/ip route $cmd $ALL dev $ALL_DEV
}

cleanup_routing()
{
	[ -z "$ALL" ] && return 0
	/sbin/ip route list | grep -E "^$ALL dev " | while read dst dev_kword iface tail; do
		/sbin/ip route del $dst dev $iface $tail
	done
}

#---------------------------------------------------------------
#
#	Main routines
#

prestart()
{
	# Nothing to do
	:
}

start()
{
	# Build program command line
	[ -n "$MAILHOSTNAME"    ] && OPTIONS="$OPTIONS -m $MAILHOSTNAME"
	[ -n "$DOMAIN_SUFFIX"   ] && OPTIONS="$OPTIONS -s $DOMAIN_SUFFIX"
	[ -n "$DHCP_LEASE"      ] && OPTIONS="$OPTIONS -l $DHCP_LEASE"
	[ -n "$RESOLV_CONF" -a -f "$RESOLV_CONF" ] && OPTIONS="$OPTIONS -r $RESOLV_CONF"
	exec /usr/sbin/dnsmasq $OPTIONS $@
}

poststart()
{
	if [ -z "$1" -o "$1" = 0 ]; then
		do_route add "Adding local broadcast host route:"
		start_resolvconf
	fi
}

poststop()
{
	stop_resolvconf
	do_route del "Removing host route defined at startup:"
}

case "$1" in
	prestart) prestart ;;
	start) shift; start "$@" ;;
	poststart) shift; poststart "$@" ;;
	poststop) poststop ;;
	cleanup_routing) cleanup_routing ;;
	*)
		echo "Usage: ${0##*/} {prestart | start [ <dnsmasq-options> ] | poststart [ <dnsmasq-status> ] | poststop | cleanup_routing}"
		exit 1
esac
