#!/bin/sh
# This shell script takes care of starting and stopping dhcpd.
# chkconfig: 345 65 35
# description: DHCP server

. /etc/init.d/functions		# Source function library.
. /etc/sysconfig/network	# Source networking configuration.

# Check that networking is up and the service exists.
[ "$NETWORKING" = "yes" -a -x /usr/sbin/dhcpd -a -s /etc/dhcpd.conf ] || exit

LOCKFILE=/var/lock/subsys/dhcpd
RETVAL=0
ALL=255.255.255.255

SED=/bin/sed
GREP=/bin/grep
IFCFG=/sbin/ifconfig

for i in /etc/sysconfig/network-scripts/ifcfg-*; do
	SourceIfNotEmpty $i
	if [ "$DHCP" = "yes" ] && [ `$IFCFG $DEVICE | $GREP -c "UP"` -gt 0 ]; then
		if [ `$GREP -cE "subnet *$NETWORK *netmask *$NETMASK" /etc/dhcpd.conf` -eq 1 ]; then
			[ -z "$DEV" ] && DEV="$DEVICE" || DEV="$DEV $DEVICE"
		fi
	fi
done

start(){
	echo -n "Starting dhcpd on $DEV:"
	daemon /usr/sbin/dhcpd `echo $DEV|$SED -e "s|:[0-9]*||g"`
	RETVAL=$?
	echo
	if [ $RETVAL -eq 0 ]; then
		echo -n "Adding local broadcast host route:"
		
		for i in $DEV; do
			daemon /sbin/route add -net $ALL netmask $ALL dev $i
		done
		echo
		touch "$LOCKFILE"
	fi
}

stop(){
	echo -n "Shutting down dhcpd:"
	killproc dhcpd
	RETVAL=$?
	echo
	if [ $RETVAL -eq 0 ]; then
		echo -n "Removing host route defined at startup:"
		for i in $DEV; do
			daemon /sbin/route del $ALL dev $i
		done
		echo
		rm -f "$LOCKFILE"
	fi
}

restart(){
	stop
	start
}

case "$1" in
	start)
		start
	;;
	stop)
		stop
	;;
	restart|reload)
		restart
	;;
	condstop)
		[ -e "$LOCKFILE" ] && stop
	;;
	condrestart)
		[ -e "$LOCKFILE" ] && restart
	;;
	status)
		status dhcpd
		RETVAL=$?
	;;
	*)
		echo "Usage: ${0##*/} {start|stop|restart|condstop|condrestart|status}"
		RETVAL=1
	;;
esac

exit $RETVAL
