#!/bin/sh
# ver 0.7
# ifpoll, poll my boss node or the node given as argument 1
#
# i start this shell script every day by crond, but you can
# start it also by hand :) start it as the owner of ifcico.
# rasca, berlin 1993 (Rasca Gmelch, 2:2410/305.4)
#

# where "ifcico" and "ifpack" reside
FIDOPATH=/usr/local/lib/ifmail
FGATE=/usr/local/lib/fidogate

# logfile of ifcico
IFLOG=/var/log/fido/ifcico.log
IFDEBUG=/var/log/fido/ifdebug.log

# owner of "ifcico"
IFCICO_OWNER=uucp

# sysop of fido stuff
IFCICO_SYSOP=root

# my boss node (default address to poll)
NODE="f2161.n2426.z2.fidonet.org"
#NODE="f2160.n2426.z2.fidonet.org"

# how often should i try to call NODE?
# MaxTry=5
MaxTry=2

# delay between outgoing calls in seconds
DELAY=40

# where to log processing - file or tty/console
# INFO_TTY=/dev/tty6


function GetConnectMessage () {
	grep 'chat got "CONNECT.*", continue' $IFLOG \
	| tail -n1 \
	| sed 's/.*chat got //;s/, continue//'
	}

function GetNoConnectMessage () {
	grep 'chat got .*, aborting' $IFLOG \
	| tail -n1 \
	| sed 's/.*chat got //;s/, aborting//'
	}

mv -f $IFDEBUG $IFDEBUG.old
touch $IFDEBUG

# echo "`date \"+%b %d %T\"` ifpoll[$$]: starting" >> $INFO_TTY
echo "`date \"+%b %d %T\"` ifpoll[$$]: starting" 

# remember me, not to run as root..
#
if [ `whoami` != "$IFCICO_OWNER" ]; then
	echo "*** run $0 as the owner of ifcico ***"
#	echo "`date \"+%b %d %T\"` ifpoll[$$]: wrong uid (rc 2)" >> $INFO_TTY
	echo "`date \"+%b %d %T\"` ifpoll[$$]: wrong uid (rc 2)"
	exit 2
fi

# argv[1] is the optional node to call
#
if [ "$1" != "" ]; then
	if [ "$1" = "-?" ] || [ "$1" = "-h" ]; then
		echo "usage: ifpoll [<node>]"
		exit 3
	else
		NODE=$1
	fi
fi

# let's pack the fido stuff..
#
# $FIDOPATH/ifpack
# 
# $FIDOPATH/fgpack

# loop until ifcico could connect the node or MaxTry is encountered
#
i=1; errlv=1
while let 'i <= MaxTry' && let 'errlv != 0'
do
#	echo -n "`date \"+%b %d %T\"` ifpoll[$$]: $i. try ($NODE) " >> $INFO_TTY
	echo -n "`date \"+%b %d %T\"` ifpoll[$$]: $i. try ($NODE) "
	#
	# start ifcico in master mode ..
	#
	$FIDOPATH/ifcico -r 1 $NODE
	errlv=$?
	if [ $errlv != "0" ]; then
#		GetNoConnectMessage >> $INFO_TTY
		GetNoConnectMessage 
		if [ $i != $MaxTry ]; then
			sleep $DELAY
		fi
		let i=i+1
	else
#		GetConnectMessage >> $INFO_TTY
		GetConnectMessage 
	fi
done

# if the poll was fine, unpacking..
#
if [ $errlv = "0" ]; then
	echo "`date \"+%b %d %T\"` ifpoll[$$]: unpacking.. " >> $INFO_TTY
#	$FIDOPATH/fgunpack $INFO_TTY
#	$FGATE/fido_run
	# add here some additional lines for processing tic files or
	# incoming file-lists or simular..
else
	# write me a mail about the failed poll
	grep 'chat got .*, aborting' $IFLOG | \
		tail -n20 | \
		elm -s "ifpoll: failed" $IFCICO_SYSOP >/dev/null
fi

# echo "`date \"+%b %d %T\"` ifpoll[$$]: finished (rc $errlv)" >> $INFO_TTY
echo "`date \"+%b %d %T\"` ifpoll[$$]: finished (rc $errlv)"

# return the errorlevel of ifcico
exit $errlv
