#!/bin/sh

# A script to restart GNS or MSF daemons: apache, pdd and sda or sdu
# If input flag -s, restart pdd only
# If input flag -a, restart pdd, apache and sda
# If input flag -u, restart pdd , apache and sdu

LD_LIBRARY_PATH=/usr/local/gwa/lib:/usr/local/lib:/usr/ucblib
export LD_LIBRARY_PATH

if [ "$1" = "-s" ] ; then
	SETONLY=1
	shift
fi

PORT=$1

if [ -z "$PORT" ]; then
	PORT=2000
fi

OFFSET=0

PATH=/usr/local/gwa/bin:.:$PATH

# If GNS, restart sda

if [ "$1" = "-a" ] ; then	## GNS
	killproc sda
	/usr/local/gwa/bin/sdad
fi

# If MSF, restart sdu

if [ "$1" = "-u" ] ; then	## MSF
	killproc sdu
	/usr/local/gwa/bin/sdud
fi


killproc pdd

# Find a pdd port which is unused

while /bin/true ; do
	#  clear
	TRY=`echo $PORT + $OFFSET | bc`
	echo Trying $TRY...
	setconf pdd system port $TRY
	if [ -n "$SETONLY" ]; then
		exit
	fi

	if /usr/local/gwa/bin/pdd ; then
# Start up the Apache daemon
		echo ""
		echo Restarting httpd
		/etc/init.d/httpd stop 2> /dev/null
		/etc/rc.d/init.d/httpd stop 2> /dev/null
		sleep 2
		/etc/init.d/httpd start 2> /dev/null
		/etc/rc.d/init.d/httpd start 2> /dev/null
		exit
	fi
	OFFSET=`echo $OFFSET + 1 | bc`
done