#!/bin/bash
#
# mulectl        Startup script for mulectl.
#
# chkconfig: 2345 12 88
# description: Syslog is the facility by which many daemons use to log \
# messages to various system log files.  It is a good idea to always \
# run mulectl.
### BEGIN INIT INFO
# Provides: $syslog
# Required-Start: $local_fs
# Required-Stop: $local_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Script for mule start/stop
# Description: Mule is a leading ESB solution 
### END INIT INFO

WORKDIR=/opt/mule/mule-enterprise-standalone-3.8.1/bin

# Default MULE Agent Port to look for
AMC_PORT=7777

LOGFILE=${WORKDIR}/../logs/mule_stdout.log

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

RETVAL=0
PIDFILE=${WORKDIR}/.mule_ee.pid

prog=mule
exec=${WORKDIR}/mule
ARGS=start
lockfile=${WORKDIR}/lock


start() {
	[ -x $exec ] || (echo "File $exec not having proper execution privileges nor does not exist..." && exit 5)

	umask 077

 

        this_pid=$(cat $PIDFILE 2>/dev/null)

        psf=$(ps h $this_pid)

        if  [ -z "$(echo $($0 status) | grep -i stopped)"  -a ! -z "$psf" ]
             then
                 echo Mule is already running on PID=$this_pid...
                 exit 127
        fi


        echo -n $"Starting Mule ...."
        nohup $exec $ARGS >>$LOGFILE 2>&1 & 

        RETVAL=$?

        #waiting for mule to be up

        while : 
            do
                listen=$(netstat -an | grep ${AMC_PORT} | grep LISTEN)
                if [ ! -z "$listen" ] 
                   then
                         break
                fi
                printf '.'
                sleep 1
    
            done

         echo "Started."

        [ $RETVAL -eq 0 ] && touch $lockfile

        return $RETVAL
}
stop() {
        echo -n $"Stopping mule ..."
        killproc -p $PIDFILE $exec
        [ $RETVAL -eq 0 ] && rm -f $lockfile
        return $RETVAL
}
rhstatus() {
        status -p "$PIDFILE" -l $prog $exec
}
restart() {
        stop
        start
}

case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  restart)
        restart
        ;;
  reload)
        exit 3
        ;;
  force-reload)
        restart
        ;;
  status)
        rhstatus
        ;;
  condrestart|try-restart)
        rhstatus >/dev/null 2>&1 || exit 0
        restart
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|condrestart|try-restart|reload|force-reload|status}"
        exit 3
esac

exit $?
