#! /bin/csh -f
#Tag 0x00FF0407

#
# DeltaVision License Starting script
# 4/28/95: JTN
#

set TMPF=/var/tmp/dv_detect.tmp
set LSLOCAL=0
set LSRUNNING=0

echo ""
echo "---- Start DeltaVision License Server ----"
echo ""

if (-e $TMPF) rm -f $TMPF
#
# Check if we're running a local or remote license server
#
if($?LSHOST == 0) then
	set LSLOCAL=1
else 
	if($LSHOST == `hostname`) then
		set LSLOCAL=1
	else
		set LSLOCAL=0
	endif
endif

#
# See if a license server process is running
#
if($LSLOCAL) then
	echo "Checking to see if a local license server is running..."
	ps -ef | grep "lserv -s" | grep -v "grep" > $TMPF
else
	echo "Checking to see if a remote license server is running..."
	rsh $LSHOST ps -ef | grep "lserv -s" | grep -v "grep" > $TMPF
endif

chmod a+rw $TMPF

#
# Count the lines in the temporary file. If there is one, then the process 
# is running.
#
set NO_LINES=`wc -l < $TMPF`

if($NO_LINES > 1) then
	echo "There seems to be more than one license server"
	echo "running on machine $LSHOST. This is an error. Please"
	echo "call Applied Precision to resolve this conflict"
	echo " "
	rm $TMPF
	exit 1
endif

if($NO_LINES > 0) set LSRUNNING=1

#
# If the license server is running, offer to let the user kill it
#
if($LSRUNNING) then
	set PS_TOKENS=(`cat $TMPF`)
	rm $TMPF
	echo Server process is owned by user: $PS_TOKENS[1], pid = $PS_TOKENS[2]

	if($LSLOCAL) then
		echo " "
		echo "It looks like a license server process is running."
		echo "If you need the license server to read a new license"
		echo "key file, you'll need to kill the existing server"
		echo "and restart. Otherwise, you shouldn't need to kill"
		echo "the existing server process."
		echo " "
		echo "Do you want to kill the current license server? (y/n) \c"
		set YN=$<
		if($YN == "Y" || $YN == "y") then
			if($PS_TOKENS[1] == $LOGNAME) then
				echo Killing Server...
				kill -9 $PS_TOKENS[2]
			else
				echo Killing Server as user $PS_TOKENS[1]...
				su $PS_TOKENS[1] -c "kill -9 $PS_TOKENS[2]"
			endif
		else
			echo No changes made to the license server.
			echo " "
			echo "Press <Enter> to continue."
			$<
			exit 1 
		endif
	else
#             
#          Don't try to kill a remotely running process...
#
		echo " "
		echo You have a license server process running on
		echo machine $LSHOST. If you want to make changes to
		echo it, you\'ll need to log in to that machine.
		echo " "
		exit 1
		
	endif
endif

#
# Now start or restart the license server using the first dvlicense encountered
# in the config directory
#
if($?DV_BASE == 0) then
	set RESULT=`grep DV_BASE ~/.dvrc`
	set DV_BASE=$RESULT[2]
endif

set DVLicenseFile = `(ls $DV_BASE/config/* | grep dvlicense)`
echo "Starting the DeltaVision License Server..."
echo " - the license is contained in $DVLicenseFile[1]"

lserv -s $DVLicenseFile[1] -t 8014

sleep 5
exit 0
