#!/bin/sh

# $Id: ddc,v 1.1 2000/12/12 11:57:48 edwin Exp $

#
# global variables, you might have to change them!
#
DHCPD=/usr/local/sbin/dhcpd
PIDFILE=/var/run/dhcpd.pid
LF=/var/db/dhcpd.leases
CF=/usr/local/etc/dhcpd.conf
#OPTIONS="-q -p 90 fxp0"
#
#

usage () {
	echo "usage: $0 <stop|start|restart|configcheck|running>"
	exit
}

configfile () {
	if [ ! -r $CF -o ! -r $LF ]; then
		echo "You can't access the config-files, sorry"
		exit 1
	fi
}

pidfile () {
	if [ ! -r $PIDFILE ]; then
		echo "You can't access the pidfile, sorry"
		exit 1
	fi
}

root () {
	if [ "`whoami`" != "root" ]; then
		echo "You must be root to use this option"
		exit 1
	fi
}

if [ -z "$1" ]; then
	usage
fi

what=$1
shift

case $what in
	start)
		root
		if [ -f $PIDFILE ]; then
			if [ -z "`ps xauw | awk '{ print $2 }' | grep -w \`cat $PIDFILE\``" ]; then
				echo "Found stale pidfile."
			else
				echo "There is already a dhcpd running, not restarted."
				exit 1
			fi
		fi
		echo "Starting dhcpd."
		$DHCPD -lf $LF -cf $CF $OPTIONS
		exit $?
		;;
	restart)
		root
		if [ -f $PIDFILE ]; then
			if [ -z "`ps xauw | awk '{ print $2 }' | grep -w \`cat $PIDFILE\``" ]; then
				echo "Found stale pidfile."
			else
				echo "Killing old dhcpd daemon."
				kill `cat $PIDFILE`
			fi
		fi
		echo "Starting dhcpd."
		$DHCPD -lf $LF -cf $CF $OPTIONS
		;;
	stop)
		root
		if [ -f $PIDFILE ]; then
			if [ -z "`ps xauw | awk '{ print $2 }' | grep -w \`cat $PIDFILE\``" ]; then
				echo "Found stale pidfile."
			else
				echo "Killing dhcpd daemon."
				kill `cat $PIDFILE`
			fi
		else
			echo "Couldn't find pidfile."
		fi
		;;
	running)
		pidfile
		if [ -f $PIDFILE ]; then
			if [ -z "`ps xauw | awk '{ print $2 }' | grep -w \`cat $PIDFILE\``" ]; then
				echo "Found stale pidfile, dhcpd is not running."
				exit 1
			else
				echo "dhcpd is running."
				exit 0
			fi
		else
			echo "dhcpd is not running."
			exit 1
		fi
		;;
	configcheck)
		configfile
		$DHCPD -t -q -cf $CF
		if [ $? = 0 ]; then
			echo "config is ok"
		else
			echo "config is NOT ok"
			$DHCPD -t -cf $CF
			exit
		fi
		$DHCPD -T -q -cf $CF -lf $LF
		if [ $? = 0 ]; then
			echo "lease-file is ok"
		else
			echo "lease-file is NOT ok"
			$DHCPD -T -cf $CF -lf $LF
			exit
		fi
		;;
	*)
		usage
		;;
esac
