#!/bin/bash
#
# beaker-provision:	Beaker power control and provisioning daemon
#
# chkconfig: - 99 99
# description:  This service acts on queued commands from the Beaker server by
# provisioning test systems and controlling power.

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

[ -f /usr/bin/beaker-provision ] || exit 0

prog="beaker-provision"
PIDFILE=/var/run/beaker-lab-controller/${prog}.pid
LOCKFILE=/var/lock/subsys/$prog

check_pidfile() {
    status -p $PIDFILE $prog >& /dev/null
    ret=$?
    if [ "$ret" -eq 1 ]; then
        # remove stale pidfile
        rm -f -- "$PIDFILE"
    fi
}

start() {
    echo -n $"Starting $prog: "
    check_pidfile
    daemon --pidfile $PIDFILE $prog
    RETVAL=$?
    echo
    if test $RETVAL = 0; then
        touch $LOCKFILE
    fi
    return $RETVAL
}

stop() {
    local pid start
    echo "Stopping $prog ..."
    echo "This may take a few moments while running commands complete."

    pid=$(pidofproc -p $PIDFILE $prog)
    RETVAL=0
    if checkpid $pid ; then
        # First send SIGTERM
        kill -TERM $pid
        RETVAL=$?
        if [ $RETVAL -eq 0 ] ; then
            # Wait for death
            start=$(date +%s)
            while [ $(($(date +%s) - start)) -lt 303 ] ; do
                checkpid $pid || break
                sleep 1
            done
            # If still alive, kill with fire
            if checkpid $pid ; then
                kill -KILL $pid
                RETVAL=$?
            fi
        fi
    fi

    rm -f $LOCKFILE
    [ $RETVAL -eq 0 ] && success || error
    echo
    return $RETVAL
}

restart() {
    stop
    start
}

condrestart(){
	[ -e $LOCKFILE ] && restart
	return 0
}

# See how we were called.
case "$1" in
    start)
	start
	;;
    stop)
	stop
	;;
    status)
	status -p $PIDFILE $prog
	RETVAL=$?
        ;;
    restart)
	restart
	;;
    condrestart)
	condrestart
	;;
    reload)
        ;;
    *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|reload}"
	;;
esac
exit $RETVAL
