#!/bin/sh
#
# kermit paging script
# SMM - moved Jacob's stuff here, 'cause real shells have no functions!
#
# Code by Jacob Lundqvist jaclu@ibk.se   
#
#   Updated 97-01-11
#
# Bugs:	Mssages can be lost if several processes tries to access kermit
# 	at the same second, I have tried to reduce this risk by
#	introducing some randomness in the sleeptimes.
#	However if one sleeps 22, and some other sleep 73 they might
#	still wake upp at the same second, if thats the case, one or
#	both messages might get lost. This is hopefully not all that serious,
#	If the error is still there the next time bb checks, a new message 
#	will be sent, the risk that the same message would be lost twice,
#	can't be that high...
#	
#

A1=$1			# FIRST ARG
shift;
A2="$*"			# ALL THE REST.  DON'T ASK.  REALLY.

if test ! "$BBTMP"                      # GET DEFINITIONS IF NEEDED
then
        . $BBHOME/etc/bbdef.sh          # INCLUDE STANDARD DEFINITIONS
fi

#-----------------------------------------------------------------------------
#  Wait for device to be available
#-----------------------------------------------------------------------------

    	TTYDEV=`echo "$TTYLINE" | sed "s/\/dev\///"`
    	#
    	# To sepparate page-requests arriving the same second, 
	# we give sleep-times depending on PID
	# 
	I=`expr $$ % 10`  		# last digit of PID
	SLEEPTIME=`expr $I + 1`		# plus 1 second
	#
	# allways do one sleep, to sepparate processes
	# starting same second in time
	#
	# echo initial sleep of:$SLEEPTIME
	sleep $SLEEPTIME 	

	while test -f ${LOCKPREFIX}${TTYDEV}  || test -f $PAGINGLOCK
    	do
		# echo "page: line busy, sleeping $SLEEPTIME"
		sleep $SLEEPTIME
    	done
    	$BBHOME/bin/touchtime 0  $PAGINGLOCK # prevent race-conditions

#-----------------------------------------------------------------------------
# Send a message using a kermit script, multiple attempts
#-----------------------------------------------------------------------------
#

    I=1
    while test $I -le 10
    do
	# echo "page; trying to send, attempt: $I"
	I=`expr $I + 1`
	$KERMIT $A1 $TTYLINE $A2 > /dev/null
	if test "$?" = "0" 
	then
	    I=999 # make sure loop ends...
	fi
    done

    $RM -f $PAGINGLOCK

# Debuging...

#    if test "$I" = "999"
#    then
#	echo "msg delivered"
#    else
#	echo "msg failed"
#    fi

