#!/bin/sh
#
# unbound	This shell script takes care of starting and stopping
#		unbound (DNS server).
#
# chkconfig:   - 14 86
# description:	unbound is a Domain Name Server (DNS) \
#		that is used to resolve host names to IP addresses.

### BEGIN INIT INFO
# Provides: $named unbound
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Should-Start: $syslog
# Should-Stop: $syslog
# Short-Description: unbound recursive Domain Name Server.
# Description:  unbound is a Domain Name Server (DNS) 
#		that is used to resolve host names to IP addresses.
### END INIT INFO

WITHOUT_RC_COMPAT=1

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

# Source networking configuration.
SourceIfNotEmpty /etc/sysconfig/network

LOCKFILE=/var/lock/subsys/unbound
RETVAL=0

anchor="/var/lib/unbound/root.key"

update_ancher()
{
	echo -n "Update root anchor:"
	unbound-anchor -a "$anchor"
	RETVAL=$?
	if [ "$RETVAL" = 0 ]; then
	    echo -n " ... no need update $anchor"
	    echo_passed
	    echo
	elif [ "$RETVAL" = 1 ]; then
	    echo -n " ... updated $anchor"
	    echo_success
	    echo
	    RETVAL=0
	else
	    echo -n " ... an error occurred"
	    echo_failure
	    echo
	fi
	chown _unbound $anchor 2> /dev/null
	return $RETVAL
}

check_conf()
{
	echo -n "Checking unbound configuration:"
	result=$(unbound-checkconf 2>&1)
	RETVAL=$?
	if [ "$RETVAL" = 0 ]; then
	    echo_success
	    echo
	else
	    echo_failure
	    echo
	    echo "$result"
	fi
	return $RETVAL
}

start()
{
	is_yes "$NETWORKING" || return 0
	update_ancher && check_conf && start_daemon --lockfile "$LOCKFILE" --expect-user _unbound -- unbound
	RETVAL=$?
	return $RETVAL
}

stop()
{
	stop_daemon --lockfile "$LOCKFILE" --expect-user _unbound -- unbound
	RETVAL=$?
	return $RETVAL
}

restart()
{
	stop
	start
}

reload()
{
	check_conf && msg_reloading unbound && stop_daemon --expect-user _unbound -HUP -- unbound
	RETVAL=$?
	return $RETVAL
}


# See how we were called.
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		restart
		;;
	status)
		status --lockfile "$LOCKFILE" --expect-user _unbound unbound
		RETVAL=$?
		;;
	reload)
		reload
		;; 
	condstop)
		if [ -e "$LOCKFILE" ]; then
			stop
		fi
		;;
	condrestart)
		if [ -e "$LOCKFILE" ]; then
			restart
		fi
		;;
	condreload)
		if [ -e "$LOCKFILE" ]; then
			reload
		fi
		;;
	*)
		msg_usage "${0##*/} {start|stop|restart|reload|status|condstop|condrestart}"
		RETVAL=1
esac

exit $RETVAL
