#!/bin/sh
# $Id: shak_checklock_v 1.4 1996/05/18 15:23:40 jhl Exp $

# shak_checklock - Check lock
# $1 is the lockhost
# $2 is the lockfile entry that is looked for.

# return values: 0 or 1
#   2: non existent lockfile
#   1: not locked
#   0: locked.
#   3: program code exception.

verify_lock=0
test=0
tapen=0

while [ $# -ge "1" ]
do
   case $1 in
      -q)
#	echo queue position.
	shift;
	verify_lock=1
        ;;
      -t)
#	echo number of this entry in the queue, should be 1 only.
	shift;
	test=1
        ;;
      -i)
#	echo currently loaded tape tapenumber
	shift;
	tapen=1
        ;;
      -*)
         echo "shak_checklock: invalid args" 1>&2
	 exit -1
         ;;
      *)
         break
         ;;
    esac
done

lockhost="$1"
lockline="$2"
lockfile="`$SHAK_LIBPATH/shak_lockname`"
lockline="`echo $lockline | sed -e 's/:[^:]*$//'`"

#echo "$lockhost" "$lockline" 1>&2

if [ $verify_lock -eq 1 ]; then
        
	queueposition="`$SHAK_LIBPATH/shak0_read_file $lockhost $lockfile`"
	if [ $? -eq 5 ]; then
#		echo -n ""
		exit 2
	fi
	queueposition="`echo "$queueposition" | grep -n "$lockline" | sed -e 's/^\([^:]*\):.*/\1/'`"
	if [ ! "$queueposition" ]; then
#		echo -n ""
		exit 1
	fi      

 	echo "$queueposition"
	exit 0
fi

if [ $test -eq 1 ]; then
        nentries="`$SHAK_LIBPATH/shak0_read_file $lockhost $lockfile`"
	if [ $? -eq 5 ]; then
#		echo -n ""
		exit 2
	fi
	nentries="`echo "$nentries" | grep "$lockline" | wc -l `"
	if [ ! "$nentries" ]; then
#		echo -n ""
		exit 1
	fi      
 	echo "$nentries"
	exit 0
fi

if [ $tapen -eq 1 ]; then
        currenttape="`$SHAK_LIBPATH/shak0_read_file $lockhost $lockfile | head -1 | sed -e 's@^[^:]*:[^:]*:@@'`"
	if [ ! "$currenttape" ]; then
		echo "0"
		exit 0
	fi      

 	echo "$currenttape"
	exit $?
fi

winningline="`$SHAK_LIBPATH/shak0_read_file $lockhost $lockfile | head -1`"
if [ ! "$winningline" ]; then
	exit 1
fi      

echo "$winningline" | grep -l "$lockline" 1>/dev/null 2>&1

if [ "$?" = "0" ]; then
	exit 0
else
	exit 1
fi


