#!/bin/sh
#
#

### BEGIN INIT INFO
# Provides:          isc-dhcp-server
# Required-Start:    $remote_fs $network $syslog
# Required-Stop:     $remote_fs $network $syslog
# Should-Start:      $local_fs slapd $named
# Should-Stop:       $local_fs slapd
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: DHCP server
# Description:       Dynamic Host Configuration Protocol Server
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin

test -f /usr/sbin/dhcpd || exit 0

DHCPD_DEFAULT="${DHCPD_DEFAULT:-/etc/default/isc-dhcp-server}"

# It is not safe to start if we don't have a default configuration...
if [ ! -f "$DHCPD_DEFAULT" ]; then
	echo "$DHCPD_DEFAULT does not exist! - Aborting..."
	if [ "$DHCPD_DEFAULT" = "/etc/default/isc-dhcp-server" ]; then
		echo "Run 'dpkg-reconfigure isc-dhcp-server' to fix the problem."
	fi
	exit 0
fi

. /lib/lsb/init-functions

# Read init script configuration
[ -f "$DHCPD_DEFAULT" ] && . "$DHCPD_DEFAULT"

NAME=dhcpd
DESC="ISC DHCP server"
# fallback to default config file
DHCPD_CONF=${DHCPD_CONF:-/etc/dhcp/dhcpd.conf}
# try to read pid file name from config file, with fallback to /var/run/dhcpd.pid
if [ -z "$DHCPD_PID" ]; then
	DHCPD_PID=$(sed -n -e 's/^[ \t]*pid-file-name[ \t]*"\(.*\)"[ \t]*;.*$/\1/p' < "$DHCPD_CONF" 2>/dev/null | head -n 1)
fi
DHCPD_PID="${DHCPD_PID:-/var/run/dhcpd.pid}"

test_config()
{
	if ! /usr/sbin/dhcpd -t $OPTIONS -q -cf "$DHCPD_CONF" > /dev/null 2>&1; then
		echo "dhcpd self-test failed. Please fix $DHCPD_CONF."
		echo "The error was: "
		/usr/sbin/dhcpd -t $OPTIONS -cf "$DHCPD_CONF"
		exit 1
	fi
	touch /var/lib/dhcp/dhcpd.leases
}

# single arg is -v for messages, -q for none
check_status()
{
    if [ ! -r "$DHCPD_PID" ]; then
	test "$1" != -v || echo "$NAME is not running."
	return 3
    fi
    if read pid < "$DHCPD_PID" && ps -p "$pid" > /dev/null 2>&1; then
	test "$1" != -v || echo "$NAME is running."
	return 0
    else
	test "$1" != -v || echo "$NAME is not running but $DHCPD_PID exists."
	return 1
    fi
}

case "$1" in
	start)
		test_config
		if [ -e "$DHCPD_PID" ]; then
			log_failure_msg "dhcpd service already running (pid file $DHCPD_PID currenty exists)"
			exit 1
		fi
		log_daemon_msg "Starting $DESC" "$NAME"
		start-stop-daemon --start --quiet --pidfile "$DHCPD_PID" \
			--exec /usr/sbin/dhcpd -- \
			-q $OPTIONS -cf "$DHCPD_CONF" -pf "$DHCPD_PID" $INTERFACES
		sleep 2

		if check_status -q; then
			log_end_msg 0
		else
			log_failure_msg "check syslog for diagnostics."
			log_end_msg 1
			exit 1
		fi
		;;
	stop)
		log_daemon_msg "Stopping $DESC" "$NAME"
		start-stop-daemon --stop --quiet --pidfile "$DHCPD_PID"
		log_end_msg $?
		rm -f "$DHCPD_PID"
		;;
	restart | force-reload)
		test_config
		$0 stop
		sleep 2
		$0 start
		if [ "$?" != "0" ]; then
			exit 1
		fi
		;;
	status)
		echo -n "Status of $DESC: "
		check_status -v
		exit "$?"
		;;
	*)
		echo "Usage: $0 {start|stop|restart|force-reload|status}"
		exit 1 
esac

exit 0
