#!/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

# First argument: command or command.instance
COMMAND="${1%%.*}"
INSTANCE="${1#*.}"
if [ "$INSTANCE" = "$1" ]; then
	INSTANCE=
fi

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

# 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="dnsmasq${INSTANCE:+@$INSTANCE}: setup resolv.conf for local resolver:"
	echo -n "$msg"
	echo 'nameserver 127.0.0.1' | "$RESOLVCONF" -a "lo.dnsmasq${INSTANCE:+.$INSTANCE}" &&
		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${INSTANCE:+.$INSTANCE}" >/dev/null 2>&1 || return 0
	action "dnsmasq${INSTANCE:+@$INSTANCE}: restore resolv.conf:" "$RESOLVCONF" -fd "lo.dnsmasq${INSTANCE:+.$INSTANCE}"
}

#---------------------------------------------------------------
#
#	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"
	[ -n "$CONFIG_DIR"      ] && OPTIONS="$OPTIONS -7 $CONFIG_DIR"
	[ -n "$DNSMASQ_OPTS"    ] && OPTIONS="$OPTIONS $DNSMASQ_OPTS"
	exec /usr/sbin/dnsmasq $OPTIONS $@
}

poststart()
{
	if [ -z "$1" -o "$1" = 0 ]; then
		start_resolvconf
	fi
}

poststop()
{
	stop_resolvconf
}

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