#!/bin/sh
#
# mcollective   Application Server for STOMP based agents
#
# chkconfig:    345 24 76
#
# description:  mcollective lets you build powerful Stomp compatible middleware clients in ruby without having to worry too
#               much about all the setup and management of a Stomp connection, it also provides stats, logging and so forth
#               as a bonus.
#
### BEGIN INIT INFO
# Provides:          mcollective
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start daemon at boot time
# Description:       Enable service provided by daemon.
### END INIT INFO

RUBYLIB=/usr/local/lib/site_ruby/1.8:$RUBYLIB
export RUBYLIB

mcollectived="/usr/sbin/mcollectived"
pidfile="/var/run/mcollectived.pid"
if [ -d /var/lock/subsys ]; then
    # RedHat/CentOS/etc who use subsys
    lockfile="/var/lock/subsys/mcollective"
else
    # The rest of them
    lockfile="/var/lock/mcollective"
fi

# Check that binary exists
if ! [ -f $mcollectived ]; then
    echo "mcollectived binary not found"
    exit 0
fi

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

# Determine if we can use the -p option to daemon, killproc, and status.
# RHEL < 5 can't.
if status | grep -q -- '-p' 2>/dev/null; then
    daemonopts="--pidfile $pidfile"
    pidopts="-p $pidfile"
fi

start() {
	echo -n "Starting mcollective: "
    daemon ${daemonopts} ${mcollectived} \
        --pid=${pidfile} --config="/etc/mcollective/server.cfg"
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && touch ${lockfile}
    return $RETVAL
}

stop() {
    echo -n "Shutting down mcollective: "
    killproc ${pidopts} -d 10 ${mcollectived}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
    return $RETVAL
}

restart() {
    stop
    start
}

rh_status() {
    status ${pidopts} ${mcollectived}
    RETVAL=$?
    return $RETVAL
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        restart
        ;;
    condrestart)
        rh_status_q || exit 0
        restart
        ;;
    status)
        rh_status
        ;;
    *)
        echo "Usage: mcollectived {start|stop|restart|condrestart|status}"
        RETVAL=2
        ;;
esac
exit $RETVAL
