#!/bin/sh

prefix=/usr/local
if [ "$prefix" = "NONE" ]
then
    prefix=/usr/local
fi

exec_prefix=${prefix}
localstatedir=${prefix}/var
sysconfdir=${prefix}/etc
bindir=${exec_prefix}/bin

if [ ! -f ${bindir}/besdaemon ]
then
    echo "BES does not appear to be installed in ${bindir}"
    exit 1
fi

piddir=${localstatedir}/run
pidfile=${piddir}/bes.pid

###########################################################################
#
# Attempts to start the BES
#
#..........................................................................
startBES()
{
    echo "Starting the BES"

    findRunningBES
    if [ $BES_RUNNING  ] 
    then
        echo "The BES is already running."
    else
	canWritePid
	if [ $WRITE_PID ]
	then
	    "${bindir}"/besdaemon $otherArgs
	    if [ $? != 0 ]
	    then
		echo "FAILED: The BES daemon did not appear to start"
	    else
		sleep 5
		findRunningBES
		if [ $BES_RUNNING ]
		then
		    echo "OK: Successfully started the BES"
		    cat "${pidfile}"
		else
		    echo "FAILED: The BES daemon did not appear to start"
		fi
	    fi
	fi
    fi
}

###########################################################################
#
# Attempts to stop the BES
#
#..........................................................................
stopBES()
{
    echo "Shutting down the BES daemon"
    findRunningBES
    if [ $BES_RUNNING ]
    then
	if [ $BES_PID ]
	then
	    kill -INT $BES_PID
	    sleep 5
	    findRunningBES
	    if [ $BES_RUNNING ]
	    then
		echo "Unable to stop the BES, PID: $BES_PID"
	    else
		echo "Successfully shut down the BES"
	    fi
	else
	    echo "Not running, but pid = $BES_PID"
	fi
    else
	echo "The BES daemon is not currently running"
    fi
}

###########################################################################
#
# Attempt to restart the BES
#
#..........................................................................
restartBES()
{
    stopBES
    if [ !$BES_RUNNING ]
    then
	startBES
    fi
}

###########################################################################
#
# Attempts to locate a running BES by using the ps command to search the 
# process stack for running instances of the besdaemon and beslistner 
# programs. All of the PID are collected and cached in the environment
# vairable "BES_PID"
#
#..........................................................................
findRunningBES()
{
    unset BES_RUNNING
    
    if [ -f "$pidfile" ]
    then
	BES_PID=`cat "$pidfile" | cut -d' ' -f2`
	BESLISTENER_PID=`$PS | grep -v grep | grep $BES_PID | grep beslistener | awk '{print $2}'`
	if [ $BESLISTENER_PID ]
	then
	    BES_RUNNING=1
	else
	    echo "BES PID file exists but process not running, cleaning up"
	    /bin/rm -f  "$pidfile"

	    BESLISTENER_PID=`$PS | grep -v grep | grep beslistener | awk '{print $2}'`
	    if [ $BESLISTENER_PID ]
	    then
		echo "BES seems to be running from a different location: $BESLISTENER_PID"
	    fi
	fi
    else
	BESLISTENER_PID=`$PS | grep -v grep | grep beslistener | awk '{print $2}'`
	if [ $BESLISTENER_PID ]
	then
	    echo "BES seems to be running from a different location: $BESLISTENER_PID"
	fi
    fi
}

###########################################################################
#
# Attempts to determine if the system is using the UCB or System V version 
# of the ps command.
#
#..........................................................................
checkPS()
{

# According to the OS/X man page, the UCB version of ps should not use the 
# dash in front of its options. On OS/X this prints a warning. jimg 10/29/07
UCB_PS="ps axww -o user,pid,command"
SYSTEM_V_PS="ps -ef -o user,pid,comm"


#echo "Checking ps syntax"

# I switched so that System V is tested first. This is because OS/X supports
# both syntaxes in a somewhat odd way and mentions that support for UCB might
# be removed in the future. jimg 10/29/07
$UCB_PS > /dev/null 2>&1
if  [ $? -eq 0 ]
then 
    PS=$UCB_PS
    #echo "Using UCB ps syntax"
else
    $SYSTEM_V_PS > /dev/null 2>&1
    if  [ $? -eq 0 ]
    then 
	PS=$SYSTEM_V_PS
	#echo "Using System V ps syntax"
    else
        echo "Cannot determine a functional version of \"ps\" command. Exiting."
        exit 1
    fi
fi
}

###########################################################################
#
# Check to see if user can write the pid file
#
#..........................................................................
canWritePid()
{
    unset WRITE_PID

    # Make sure we can write the pid file! jhrg 3/31/2007
    if [ ! -x ${piddir} ] || [ ! -w ${piddir} ]
    then
	echo "The besctl command cannot write to ${piddir}."
	echo "Check that the directory exists and that the user running"
	echo "besctl has write permissions for it."
    else
	WRITE_PID=1
    fi
}

checkPS

what=$1
shift
otherArgs=$*

###########################################################################
#
# Check for the BES command line options
# Any changes made here also need to be changed in daemon.cc and
# ServerApp.cc
#
#..........................................................................
dashi="no"
dashc="no"
dashr="no"
args=`getopt hvsd:c:p:u:i:r: $*`
if [ $? != 0 ]
then
    echo 'Usage: ...'
    exit 2
fi
set -- $args

for param
do
    case $param in
	-i)
	    prefix=$2
	    piddir=${prefix}/var/run
	    pidfile=${piddir}/bes.pid
	    bindir=${prefix}/bin
	    dashi="yes"
	    shift
	    shift
	    ;;
	-c)
	    dashc=$2
	    shift
	    shift
	    ;;
	-r)
	    dashr=$2
	    pidfile=${2}/bes.pid
	    shift
	    shift
	    ;;
	-d|-p|-u)
	    shift
	    shift
	    ;;
	-h|-v|-s)
	    shift
	    ;;
	--)
	    shift
	    break;;
    esac
done

echo "BES install directory: ${prefix}"

if [ "$dashi" = "no" ]
then
    otherArgs="${otherArgs} -i ${prefix}"
fi

if [ "$dashc" = "no" ]
then
    if [ $BES_CONF ]
    then
	echo "BES configuration file: ${BES_CONF}"
	otherArgs="${otherArgs} -c ${BES_CONF}"
    else
	echo "BES configuration file: ${sysconfdir}/bes/bes.conf"
	otherArgs="${otherArgs} -c ${sysconfdir}/bes/bes.conf"
    fi
else
    echo "BES configuration file: $dashc"
fi

if [ "$dashr" = "no" ]
then
    otherArgs="${otherArgs} -r ${piddir}"
fi

case $what in
stop)
    stopBES
    ;;
start)
    startBES
    ;;
restart)
    restartBES
    ;;
status)
    if [ ! -f "${pidfile}" ]
    then
	echo "The BES daemon is not currently running"
	exit 1
    fi
    echo "The BES daemon is currently running"
    cat "${pidfile}"
    ;;
*)
    echo "USAGE: besctl (start|stop|restart|status) [options]"
    echo "where [options] are passed to besdaemon; see besdaemon -h"
    exit 1
    ;;
esac

