#!/bin/sh

# edit to load from appropriate directory - done by client_install
BCNUHOME="/usr/local/bcnu"

# shouldn't need to change below here

. $BCNUHOME/etc/bcnuenv
. $BCNUHOME/etc/bcnuenv.$BCNUSERVER


run_proxy()
{
	# run proxy to send start/stop message to master
	BCNUMASTER=`grep "^agent:proxy:.*:enabled:.*:" $BCNUHOME/etc/agents | cut -d: -f7`
	if [ $BCNUMASTER ]
	then
		$RUN "BCNUPARAM=$BCNUMASTER;export BCNUPARAM; $BCNUHOME/agent/proxy $BCNUHOST"
	fi
}

# read local settings
if [ -r $BCNUHOME/etc/bcnulocal ]
        then
                . $BCNUHOME/etc/bcnulocal
fi

# run as BCNUUSER if I am being started by root
if [ "$LOGNAME" = "root" -o "$USER" = "root" -o -z "$LOGNAME" ]
	then
		RUN="su $BCNUUSER -c "
	else
		RUN="eval "
fi

# Start/stop processes required for server bcnud

case "$1" in
'start'|'start_with_proxy')

	if [ -x $BCNUHOME/bin/bcnud ] 
		then
			# start server
			$RUN "$BCNUHOME/bin/bcnud -s $BCNUPORT $2 $BCNUHOST >$BCNUHOME/logs/bcnud.log 2>&1 </dev/null"
			# log startup using av agent
			$RUN "$BCNUHOME/agent/av $BCNUHOST av 0 start"
			if [ "$1" = "start_with_proxy" ] ; then
		  	  # run proxy agent for immediate forwarding
	  		  run_proxy
			fi
	fi
	;;

'stop'|'stop_with_proxy')
	if [ -s $BCNUHOME/etc/bcnud.pid ]
	   then
		# log shutdown using av agent
		$RUN "$BCNUHOME/agent/av $BCNUHOST av 0 stop"
		if [ "$1" = "stop_with_proxy" ] ; then
		  # run proxy agent for immediate forwarding
		  run_proxy
		fi
		PID=`cat $BCNUHOME/etc/bcnud.pid`
		kill $PID 2>/dev/null
		sleep 1
		if kill -0 $PID 2>/dev/null
	   	then
			kill -9 $PID 2>/dev/null
		fi
	fi
	rm -f $BCNUHOME/etc/bcnud.pid
	;;

'restart')
	echo "stopping bcnud.."
        $BCNUHOME/etc/bcnud_server stop
	echo "starting bcnud.."
        $BCNUHOME/etc/bcnud_server start $2
	echo "bcnud restarted.."
        $BCNUHOME/bin/bcnu -s $BCNUPORT -a show localhost
        ;;

*)
        echo "Usage: $0 { start | start_with_proxy | stop | stop_with_proxy | restart }"
        ;;

esac
