#!/bin/bash
#
#  dhcdbd  :  DHcp Client D-Bus Daemon
#
#  chkconfig: - 98 02
#  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
#
#  dhcdbd shuts down automatically when the messagebus is shut down .
#
. /etc/rc.d/init.d/functions
prog=dhcdbd
lockfile=/var/lock/subsys/dhcdbd
busfile=/var/run/dbus/system_bus_socket
dhcdbd=/sbin/dhcdbd
PID=/var/run/dhcdbd.pid
start() {
    if start-stop-daemon --start --test --quiet --pidfile "$PID" \
	--exec "$dhcdbd" >/dev/null; then
	action "Starting $prog:" \
	    start-stop-daemon --start -b -m --pidfile "$PID" -x $dhcdbd -- "--system"
    else
        msg_already_running $prog
        passed "$prog startup"
        echo
    fi
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch $lockfile
    return $RETVAL;
}

stop () {
	if [ -e $lockfile ] && [ -e $busfile ]; then
	    action "Stopping $prog:" \
	    /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
	else
	    action "Stopping $prog:" \
	    start-stop-daemon --stop --pidfile "$PID"
	fi;
	rm -f $lockfile
}

status() {
        pid=`cat $PID`;
	RETVAL=$?
	if [ "$RETVAL" -eq 0 ] && [ -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/\ .*$//'`;
	    RETVAL=$?
	    if [ "$RETVAL" -eq 0 ]; then
		echo -n $"$prog ( $pid ) listening on $sender"
		success;
		echo;
	    else
	        failure;
		echo;
	    fi;
	fi;
	return $RETVAL;
}

case "$1" in
  start) 
	start ;
	RETVAL=$?;
	;;
  stop) stop  ;
	RETVAL=$?;
	;;
  condrestart)
	if [ -e $lockfile ] && [ -e $busfile ] && [ -e /proc/`cat /var/run/dhcdbd.pid` ]; then
	    stop ;
	    start;
	    RETVAL=$?;
	fi;
	;;
  restart|reload)
	stop ;
	start;
	RETVAL=$?;
        ;;
  status)
        status;
	RETVAL=$?;
	;;
  *)
        echo $"$prog: Usage: < start | stop | restart | reload | status >"
	;;
esac;

exit $RETVAL;

