#!/bin/sh

NODE=/usr/bin/node
WD=/mnt/internal/node/broker
JS=/mnt/internal/node/broker/broker.js
ARGS="" 
PIDFILE=/var/run/broker.pid
LOG=/var/log/debug/broker.log
PID=0

NODE_PATH=/mnt/internal/node/lib/node_modules
export NODE_PATH


# First check and see if there is already a broker "wrapper" (This script) running.
#  If so then lets just exit so we don't end up trying to spawn multiple instances
#  of the broker.
if [ -e ${PIDFILE} ]; then
	echo "PIDFILE Exists" >> ${LOG}
	PID=$(cat ${PIDFILE})
	echo "WITH PID: ${PID}" >> ${LOG}
fi

if [ -e /proc/${PID} ]; then
	echo "Process Already Running.  Not Restarting." >> ${LOG}
	exit 1
else
	echo "PID ${PID} is not active.  Restarting." >> ${LOG}
fi

# Occasionally a node process can be left running if this script gets killed with -9.
# Check for orphaned node processes and kill them.
killall -HUP node

# Now that we think we're not running, lets start the node process with the proper 
#  javascript file.  We must be in the broker directory for this to work.
echo "Starting the broker." >> ${LOG}
cd ${WD}
${NODE} ${JS} ${ARGS} >> ${LOG} 2>&1 &
PID=$!

# Trap signals so when sysman tells us to die, we kill the process we're managing as well.
trap 'echo "KILLING BROKER ON DISABLE" >> ${LOG}; kill -9 ${PID}' INT TERM EXIT

echo "Started Broker.  New PID is: ${PID}" >> ${LOG}

# Now a bit of trickiness.  Because sysman only knows about this shell script we need to 
#  set OUR pid in the pidfile.  This is so when sysman checks the process with the right 
#  name and the right pid are both running.  I tried keeping the PID of the node process
#  in here and sysman kept thinking it needed to restart the process despite the fact
#  that the pid in the file was active.
echo $$ > ${PIDFILE}

# Now wait on the process we started.  If it ever exits, we will exit, and the pid in the
#  pid file will not be valid and sysman will restart us.
wait ${PID}

exit 0


