#!/bin/sh

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

exec_prefix=/usr
localstatedir=/var
bindir=/usr/bin
sysconfdir=/etc

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

conf=${BES_CONF}
if [ ! -f "${conf}" ]
then
    conf=${sysconfdir}/bes/bes.conf
    if [ ! -f "${conf}" ]
    then
	echo "The BES configuration file cannot be located at ${conf}"
    fi
fi
echo "BES configuration file: ${conf}"

what=$1
shift

case $what in
stop)
    if [ ! -f "${localstatedir}"/run/bes.pid ]
    then
	echo "The BES daemon is not currently running"
	exit 1
    fi
    echo "Shutting down the BES daemon"
    (cat "$localstatedir"/run/bes.pid | cut -d' ' -f2 | xargs kill -INT) 2> /dev/null
    ;;
start)
    # Make sure we can write the pid file! jhrg 3/31/2007
    if [ ! -x ${localstatedir}/run ] || [ ! -w ${localstatedir}/run ]
    then
	echo "The besctl command cannot write to ${localstatedir}/run."
	echo "Check that the directory exists and that the user running"
	echo "besctl has write permissions for it."
	exit 1
    fi
    # Check if the process is running too and if not rm the file and start.
    if [ -f "${localstatedir}"/run/bes.pid ]
    then
	echo "The BES daemon is already running"
	cat "${localstatedir}"/run/bes.pid
	exit 1
    fi
    echo "Starting the BES daemon"
    "${bindir}"/besdaemon $*
    sleep 5
    if [ -f "${localstatedir}"/run/bes.pid ]
    then
	cat "${localstatedir}"/run/bes.pid
    else
	echo "The BES daemon did not appear to start"
    fi
    ;;
restart)
    if [ ! -f "${localstatedir}"/run/bes.pid ]
    then
	echo "The BES daemon is not currently running"
	exit 1
    fi
    echo "Shutting down the BES daemon"
    (cat "${localstatedir}"/run/bes.pid | cut -d' ' -f2 | xargs kill -INT) 2> /dev/null
    sleep 5
    if [ -f ${localstatedir}/run/bes.pid ]
    then
	echo "Unable to stop the BES daemon"
	exit 1
    fi
    echo "Starting the BES daemon"
    "${bindir}"/besdaemon $*
    sleep 5
    if [ -f "${localstatedir}"/run/bes.pid ]
    then
	cat "${localstatedir}"/run/bes.pid
    else
	echo "The BES daemon did not appear to start"
    fi
    ;;
status)
    if [ ! -f "${localstatedir}"/run/bes.pid ]
    then
	echo "The BES daemon is not currently running"
	exit 1
    fi
    echo "The BES daemon is currently running"
    cat "${localstatedir}"/run/bes.pid
    ;;
config)
    conf=${BES_CONF}
    if [ ! -f "${conf}" ]
    then
	conf=${sysconfdir}/bes/bes.conf
	if [ ! -f "${conf}" ]
	then
	    echo "The BES configuration file cannot be located at ${conf}"
	    exit 1
	fi
    fi
    echo ""
    echo "**************************************************************"
    cat "${conf}"
    echo "**************************************************************"
    ;;
*)
    echo "USAGE: besctl (start|stop|restart|status|config)"
    exit 1
    ;;
esac

