#!/bin/sh 
#
# kermit paging script
# SMM - moved Jacob's stuff here, 'cause real shells have no functions!
#
# This program is Copyright (c) 1998
# Sean MacGuire - The MacLawran Group Inc.
# Robert-Andre Croteau, The MacLawran Group Inc.
# All Rights Reserved
# Apr 17, 1998
#
# 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
#-----------------------------------------------------------------------------

    	#
    	# To separate 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
	MAXSLEEPS=`expr 60 / $SLEEPTIME + 2`
	#
	# allways do one sleep, to separate processes
	# starting same second in time
	#
	# echo initial sleep of:$SLEEPTIME
	sleep $SLEEPTIME 	

	foundtty=FALSE
	while [ "$foundtty" = "FALSE" ]
	do
		for ttyline in $TTYLINE
		do
    			TTYDEV=`echo "$ttyline" | sed "s/\/dev\///"`
			if test -f ${LOCKPREFIX}${TTYDEV}  || test -f ${PAGINGLOCK}_${TTYDEV}
    			then
				# echo "page: line busy, sleeping $SLEEPTIME"
				sleep $SLEEPTIME
				MAXSLEEPS=`expr $MAXSLEEPS - 1`
				if [ "$MAXSLEEPS" -lt 0 ]
				then
					echo "Couldn't send page, locks weren't freed" | $MAIL "BB Pager problem" $BBMASTER
					exit 1
				fi
				# Try next modem line in TTYLINE
			else
				foundtty=TRUE
				break;
			fi	
    		done
	done

$TOUCH ${PAGINGLOCK}_${TTYDEV} # 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}_${TTYDEV}

# Debuging...

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

