#!/usr/bin/perl
#
# poll [-all] [-max NUM] [ADDR [ADDR]+]
#
# '.' is boss node (first profile entry in .feddirc)
# noarg is '.'
# -all calls until all boxes are accessed or have reached maxtries
#      default is to break after first successful call
# -max defines the maxtries
#

require 'newgetopt.pl';

$opt_max=3;
NGetOpt('max=n','all');

if ($#ARGV==-1) {
    $addresses[0]='.';
} else {
    @addresses=@ARGV;
}

open(err,"/usr/local/lib/ifmail/errors");
@ERROR=<err>;
close(err);

foreach $addr (@addresses) {
    open(NL,"fnlc -q $addr |") || die "Can't exec fnlc!\n";
    $last=0;
    $prBOX="";
  FIND: while (<NL>) {
      if (/^#Box: (.+)/) {
	  $prBOX=$1;
      }
      if (/^#Address: (\d+):(\d+)\/(\d+)\.(\d+)/) {
	  $ifADDR="f$3.n$2.z$1";
	  $prADDR="$1:$2/$3";
	  $last=1;
      }
      if (/(^##NODELIST_ENTRY##$)|(^###NODELIST_END###)/ && $last) {
	  push @prB,$prBOX;
	  push @ifA,$ifADDR;
	  push @prA,$prADDR;
	  push @tries,0;
	  print "Parsed: $prBOX($prADDR)[$ifADDR]\n";
	  last FIND;
      }
  }
    close(NL);
}

  CALL: for ($box=0; $box<=$#tries; $box++) {
      print "Calling $prA[$box] ($prB[$box])\n";
      if ($tries[$box]<$opt_max) {
	  $err=system("/usr/local/lib/ifmail/ifcico -r1 -I$ENV{'HOME'}/.ifcicorc $ifA[$box]");
	  $err/=256;
	  if ($err>$#ERROR) {
	      print "Unknown error...\n";
	  } else {
	      print $ERROR[$err];
	  }
	  if ($err) {
	      sleep 30;
	  } else {
	      if (!$opt_all) {
		  last CALL;
	      }
	      $tries[$box]++;
	  }
      }
  }
