#!/bin/sh
# ahbpoll, poll the two lines of my boss node
#
# This script is based on the original ifpoll by Rasca Gmelch
# Copyright (C) 1997 by Marco d'Itri, 2:332/206.10 / md@linux.it

. /etc/ifmail/ifshellvars

# Max number of failed polls
MaxTry=8
# delay between outgoing calls in seconds
DELAY=60

###############################################################################
# start some tail(1)s and initialize the ^C handler
{ tail -n0 -f $IFLOG > $INFO_TTY & }; TOKILL=$!
##{ tail -n0 -f $IFLOG | grep "received" & }; TOKILL="$TOKILL $!"
##{ tail -n0 -f $IFLOG | grep "sent" & }; TOKILL="$TOKILL $!"

trap "killall -HUP ifcico; kill $TOKILL; echo -e 'Aborted\n'; exit 100;" INT

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

###############################################################################
# loop until ifcico could connect the node or MaxTry is encountered
i=1; errlv=1; alternate=0
while [ $i -le $MaxTry -a $errlv != 0 ]; do
  if   [ $alternate = 0 ]; then
    NODE=f206.n332.z2.fidonet.org
    alternate=1
  elif [ $alternate = 1 ]; then
    NODE=f207.n332.z2.fidonet.org
    alternate=0
  fi

  echo -n "ahbpoll[$$]: $i. try ($NODE) "
  $IFBIN/ifcico -r 1 $NODE
  errlv=$?
  case "$errlv" in
  "0")
      echo "ok :)"
      ;;
  "2")
      echo 'failed: busy (rc 2)'
      if [ $i != $MaxTry -a $alternate = 0 ]; then sleep $DELAY; fi
      ;;
  "3")
      echo 'failed: system error (rc 3)'
      ;;
  "11")
      echo 'failed: lost carrier (rc 11)'
      if [ $i != $MaxTry -a $alternate = 0 ]; then sleep $(($DELAY+120)); fi
      ;;
  *)
      echo "failed: ?? (rc $errlv)"
      if [ $i != $MaxTry -a $alternate = 0 ]; then sleep $DELAY; fi
      ;;
  esac
  i=$(($i+1))
done

###############################################################################
# if the poll was ok, unpack
if [ $errlv = "0" ]; then
  if [ "`echo $IFSPOOL/inb/0000fff6.*`" != "$IFSPOOL/inb/0000fff6.*" ]; then
    cp --force --link --preserve \
       $IFSPOOL/inb/0000fff6.* $IFSPOOL/BAK
  fi
  $IFBIN/ifunpack
  find $IFSPOOL/BAK  -mtime +3 -type f -exec rm -fv \{\} \; >/dev/null
  find $IFSPOOL/outb -empty    -type f -exec rm -fv \{\} \; >/dev/null
fi

###############################################################################
# Kill tail(s)
kill $TOKILL

# return the errorlevel of ifcico
exit $errlv
