#!/usr/bin/perl
#
# MailPlex v1.1
# (l) Peter Baudis <pasky@ji.cz> 2001
#
# Test if mailbox is free now
# Executed for every user every $delay/$sdelay
#
# Parameters: isfree.pl <username>
#
# Prints 0 if it's empty or non-zero undef value if it isn't
#

# Configuration:

$uname=$ARGV[0];          # nope, this isn't any configurable value, ignore it
$mbox="/var/mail/$uname"; # /home/$uname/Mailbox for qmail,
                          # /var/spool/mail/$uname might be
		          # another interesting choice
			  
$simpleantidummy=1;       # simple protection against dummy messages in
			  # mailboxes dropped by some evil pop3 daemons
			  # just mailbox with size <1024b will be taken
			  # as an empty one - this should eliminate dummy
			  # messages and otherwise isn't so terrible - short
			  # messages won't make operator busy so much ;-)
			  
$antidummy=0;             # protection against dummy messages in mailboxes
                          # dropped by some evil pop3 daemons - don't use it
			  # unless you are having problems with it, it puts
			  # more load to out poor processor(s) ;-)
			  
			  # IMPORTANT NOTE: You will have to assure that
			  # this script will be able to read operators'
			  # mailboxes, which you normally won't have.

			  # another note: this option is EXPERIMENTAL and UNTESTED
			  
$nodetect=0;              # take EVERYTIME one message in mailbox as empty
                          # mailbox! use it ONLY if autodetection of dummy
			  # messages will fail and you cannot write your own
			  # one, otherwise it won't just work properly
			  # this option has effect only if you will set $antidummy
			  # on

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

if ($simpleantidummy and $antidummy) { die "Configuration error - you cannot have both \$simpleantidummy and \$antidummy.\n" }
if ($nodetect and not $antidummy) { die "Configuration error - you cannot have \$nodetect, but not \$antidummy.\n" }

## old version - just so simple
unless ($antidummy) {
  if (!(@ms=stat($mbox))) { die "Cannot stat $mbox!"; }
  if ($simpleantidummy and $ms[7]<1024) {
    print 0,"\n";
  } else {
    print $ms[7],"\n";
  }
}
## XXX - some evil pop3 daemons are leaving some dummy message there :-(
## So we have to try to detect it and take it as empty mailbox
else {
  use Mail::Util qw(read_mbox);
  
  @mailbox=read_mbox($mbox);
  
  if ($nodetect) {
    if (@mailbox>1) { print @mailbox-1; } else { print 0; }
  } else {
    use Mail::Internet;
    use Mail::Header;
    
    @firstmsg=@{$mailbox[0]};
    $msg=new Mail::Internet @firstmsg;
    $hdr=$msg->head();
    $dummy=0;

    # Now main autodetection stuff
    if ($hrd->get("Subject")=~/folder internal data/i) { $dummy=1 }

    # And print the results
    if ($dummy) {
      print 0;
    } else {
      print @mailbox;
    }
  }
  print "\n";
}
