#!/bin/sh
# ifpoll, poll my boss node or the node given as argument 1
#
# 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

# my boss node (default address to poll)
NODE="f206.n332.z2.fidonet.org"
# Max number of failed polls
MaxTry=8
# delay between outgoing calls in seconds
DELAY=60

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

###############################################################################
# start some tail(1)s and initialize the ^C handler
if [ -n "$INFO_TTY" ]; then
  { 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
else
  trap "killall -HUP ifcico; echo -e 'Aborted\n'; exit 100;" INT
fi

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

###############################################################################
# loop until ifcico could connect the node or MaxTry is encountered
i=1; errlv=1
while [ $i -le $MaxTry -a $errlv != 0 ]; do
  echo -n "ifpoll[$$]: $i. try ($NODE) "
  $IFBIN/ifcico -r 1 $NODE
  errlv=$?
  case "$errlv" in
  "0")
      echo "ok :)"
      ;;
  "2")
      echo 'failed: busy (rc 2)'
      if [ $i != $MaxTry ]; then sleep $DELAY; fi
      ;;
  "3")
      echo 'failed: system error (rc 3)'
      ;;
  "11")
      echo 'failed: lost carrier (rc 11)'
      if [ $i != $MaxTry ]; then sleep $(($DELAY+120)); fi
      ;;
  *)
      echo "failed: ?? (rc $errlv)"
      if [ $i != $MaxTry ]; 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)
if [ ! -z "$INFO_TTY" ]; then
  kill $TOKILL
fi

# return the errorlevel of ifcico
exit $errlv
