#!/bin/sh
#
# dhcdbd	DHCP Client D-BUS Daemon
#
# chkconfig:	345 89 11
# description:	dhcdbd provides D-BUS control of the ISC DHCP client, dhclient,
#		and D-BUS access to the DHCP options obtained by dhclient
#		for each IPv4 interface.
# processname:	dhcdbd
# pidfile:	/var/run/dhcdbd.pid
# config:	/etc/dbus-1/system.d/dhcdbd.conf
#
# $Id: dhcdbd.init,v 1.7 2008/07/25 12:28:32 glen Exp $

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

# Get network config
. /etc/sysconfig/network

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

# 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 dhcdbd
		exit 1
	fi
else
	exit 0
fi

start() {
  	if [ -f /var/lock/subsys/messagebus ]; then
		if [ ! -f /var/lock/subsys/dhcdbd ]; then
			msg_starting dhcdbd
			daemon /usr/sbin/dhcdbd --system
			RETVAL=$?
			[ $RETVAL -eq 0 ] && touch /var/lock/subsys/dhcdbd
		else
			msg_already_running dhcdbd
		fi
	else
		msg_not_running messagebus
	fi
}

stop() {
  	msg_stopping dhcdbd
  	if [ -f /var/run/dhcdbd.pid ]; then
		checkpid `cat /var/run/dhcdbd.pid` >/dev/null 2>&1
		if [ $? -eq 1 ]; then
			rm -f /var/lock/subsys/dhcdbd /var/run/dhcdbd.pid >/dev/null 2>&1
			died
			exit 0
		fi
	fi
  	if [ -f /var/lock/subsys/messagebus ]; then
		if [ -f /var/lock/subsys/dhcdbd ]; then
			/usr/bin/dbus-send \
				--system \
				--dest=com.redhat.dhcp \
				--type=method_call \
				--print-reply \
				--reply-timeout=20000 \
				/com/redhat/dhcp \
				com.redhat.dhcp.quit >/dev/null 2>&1
			if [ $? -eq 0 ]; then
				ok
			else
				fail
			fi
			rm -f /var/lock/subsys/dhcdbd /var/run/dhcdbd.pid >/dev/null 2>&1
		else
			msg_not_running dhcdbd
		fi
	else
		msg_not_running messagebus
	fi
}

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

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	status dhcdbd
	if [ $? -eq 0 ]; then
		pid=`cat /var/run/dhcdbd.pid`
		if [ $? -eq 0 -a -n "$pid" ]; then
			sender=`/usr/bin/dbus-send \
					--system \
					--dest=com.redhat.dhcp \
					--type=method_call \
					--print-reply \
					--reply-timeout=20000 \
					/com/redhat/dhcp \
					com.redhat.dhcp.ping |
				grep 'sender=' | sed 's/^.*sender=//;s/\ .*$//'`
			if [ $? -eq 0 ]; then
				echo 'it is listening on '$sender
			fi
		fi
	fi
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
	;;
esac

exit $RETVAL
