#! /bin/sh
#
# onapp-messaging   OnApp Messaging Infrastructure Enpoint
#
# chkconfig:        2345 98 02
# description:      onapp-messaging is a utility to manage
#                   state of local Messaging Endpoint,
#                   which provides an access to OnApp Infrastructure
#                   via Message Queueing system
#
# processname:      onapp-messaging.py
# pidfile:          /home/mq/onapp-messaging.pid

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

APPPATH=/home/mq
MESSAGING=onapp-messaging
ENDPOINT=$APPPATH/$MESSAGING
LOCK=/var/lock/subsys/$MESSAGING
PIDFILE=$APPPATH/$MESSAGING.pid
HVCONFIG=/etc/onapp.conf

print_success(){
    echo_success
    echo
}

print_failure(){
    echo_failure
    echo
}

get_pid(){
    pgrep -f "python $MESSAGING.py" | tail -n1
}

RETVAL=0

case "$1" in
    start)
        if [ ! -f $ENDPOINT.py ]; then
          echo "Can't use $ENDPOINT"
          print_failure && exit 2
        fi

        echo -n "Starting OnApp Messaging Enpoint: "
        PID=`get_pid`
        if [ ! -z $PID ]; then
            echo "Another Enpoint is active: ${PID}"
            print_failure && exit 1
        fi
        su mq -c "cd $APPPATH && python $MESSAGING.py" > /dev/null &
        RETVAL=$?
        echo
        if [ $RETVAL = 0 ]; then
            touch $LOCK
            print_success
        else
            print_failure
        fi
        ;;
    stop)
        echo -n "Stopping OnApp Messaging Enpoint: "
        PID=`get_pid`
        if [ ! $PID ]; then
            echo "Messaging Enpoint is offline"
            print_failure
            RETVAL=1
        else
            kill `get_pid` > /dev/null
            RETVAL=$?

            if [ $RETVAL = 0 ]; then
                rm -f $LOCK && rm -f $PIDFILE
                print_success
            else
                print_failure
            fi
        fi
        ;;
    restart)
        $0 stop
        $0 start
        RETVAL=$?
        ;;
    condrestart)
        [ -e $LOCK ] && $0 restart
        ;;
    status)
        PID=`get_pid`
        if [ $PID ]; then
            echo "Messaging Enpoint is active: ${PID}"
            RETVAL=0
        else
            echo "Messaging Enpoint is offline"
            RETVAL=1
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|condrestart|status}"
        exit 1
esac

exit $RETVAL
