#!/usr/bin/perl -w
#
# MailPlex v1.1
# (l) Peter Baudis <pasky@ji.cz> 2001
#
# Mail multiplexer - send queued mails to ready operators
#
# Main script
#
# Parameters: multi.pl <nothing>
#
# Takes nothing, returns nothing unless $debug != 0
#

# Configuration:

@rcpts=qw(foo bar); # recepitients
$delay=30;          # delay between checks
$sdelay=5;          # short delay between deliveries - to give MTA some time
                    # for mail delivery

$mailget='./mailget.pl'; # script for getting mail from my mailbox
$resend='./resend.pl';   # script for re-sending mail to specified recepitient
$isfree='./isfree.pl';   # script for checking operators' mailboxes

$debug=1;           # set to zero if you want to get rid of debug msgs

#### End of configuration
#### You shouldn't be interested in the rest of file, really, unless you know
#### what are you doing.

@queue=@rcpts;
foreach (@queue) { $rc{$_}->{queued}=1; }
$mailok=0;

while(1) {

  # check all mailboxes and update @queue
  foreach (@rcpts) {
    $rc{$_}->{size}=`$isfree $_`; chomp($rc{$_}->{size});
    print "Probed operator $_, mailbox $rc{$_}->{size}, queued $rc{$_}->{queued}...\n" if ($debug);
    if ($rc{$_}->{size} and $rc{$_}->{queued}) {
      splice(@queue, member($_, @queue), 1);
      $rc{$_}->{queued}=0;
      print "Operator $_ left queue w/o getting mail from me!\n" if ($debug);
    } elsif (!$rc{$_}->{size} and !$rc{$_}->{queued}) {
      push(@queue, $_);
      $rc{$_}->{queued}=1;
      print "Operator $_ joined queue.\n" if ($debug);
    }
  }
  
  $waiting=`$mailget`; chomp($waiting);
  $ready=@queue;

  print "Waiting $waiting messages, $ready operators ready [@queue].\n" if ($debug);
  
  # mail waiting for us and someone ready?
  if ($ready and $waiting) {
    $foo=`$mailget get | $resend $queue[0]`;
    print "Mail left to $queue[0], deleting from queue...\n" if ($debug);
    $rc{shift(@queue)}->{queued}=0;
    $mailok=1;
  }

  # have a rest
  if (!$mailok) {
    print "No mail left, sleeping ${delay}s...\n" if ($debug);
    sleep $delay;
  } else {
    print "Mail left, sleeping ${sdelay}s...\n" if ($debug);
    sleep $sdelay;
  }
  $mailok=0;
}

sub member {
  my($pos, $f);
  $f=shift;
  for ($pos=0; $pos<@_; $pos++) { if ($_[$pos] eq $f) { return $pos; } }
  return -1;
}
