#!/bin/sh
# DHCP Server
#
# chkconfig:	345 80 20
# description:	DHCP Server

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

# Get network config
. /etc/sysconfig/network

# Get service config
[ -f /etc/sysconfig/dhcpd ] && . /etc/sysconfig/dhcpd

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "DHCP Server"
		exit 1
	fi
else
	exit 0
fi

check_device_up()
{
	local DEVICE=$1
	if LC_ALL=C ip addr show dev $DEVICE | grep -q inet; then
		return 0
	else
		return 1
	fi
}

# configtest itself
configtest() {
	local rc out
	out=`/sbin/dhcpd -t 2>&1`; rc=$?
	if [ $rc -gt 0 ]; then
		echo >&2 "$out"
	fi

	# check if interfaces specified exist and have addresses
	for i in $DHCPD_INTERFACES; do
		if ! check_device_up $i; then
			echo >&2 "Device '$i' does not exist or has no address configured"
			rc=1
		fi
	done

	return $rc
}

# wrapper for configtest:
checkconfig() {
	local details=${1:-0}

	if [ $details = 1 ]; then
		# run config test and display report (status action)
		show "Checking %s configuration" "DHCP Server"; busy; echo
		configtest
		RETVAL=$?
	else
		# run config test and abort with nice message if failed
		# (for actions checking status before action).
		configtest >/dev/null 2>&1
		RETVAL=$?
		if [ $RETVAL != 0 ]; then
			show "Checking %s configuration" "DHCP Server"; fail
			echo >&2 "Configuration test failed. Run \"$0 checkconfig\" to see errors."
			exit $RETVAL
		fi
	fi
}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/dhcpd ]; then
		msg_already_running "DHCP Server"
		return
	fi

	checkconfig
	msg_starting "DHCP Server"
	daemon /sbin/dhcpd $DHCPD_INTERFACES
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/dhcpd
}

stop() {
	if [ ! -f /var/lock/subsys/dhcpd ]; then
		msg_not_running "DHCP Server"
		return
	fi

	msg_stopping "DHCP Server"
	killproc dhcpd
	rm -f /var/run/dhcpd.pid /var/lock/subsys/dhcpd >/dev/null 2>&1
}

condrestart() {
	if [ -f /var/lock/subsys/dhcpd ]; then
		checkconfig
		stop
		start
	else
		msg_not_running dhcpd
		RETVAL=$1
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	checkconfig
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  checkconfig)
	checkconfig 1
	;;
  status)
	status dhcpd
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|checkconfig|status}"
	exit 3
esac

exit $RETVAL
