#! /usr/bin/perl -w
# Release a file in the TMDA pending directory which is listed in the Subject.

use strict;

my $USER = $ENV{"USER"};
my $HostName = `hostname`;
my $HOME_DIR = "$ENV{\"HOME\"}";
my $TMDA_DIR = "$HOME_DIR/.tmda";
my $untainted_pending_file = "none";
my $command = "none";
my $function = "none";
my $whitelist_address = "none";

if ( ! -f "$TMDA_DIR/config" )
   {
   die "Can't find config file.\n";
   }

chdir( "$HOME_DIR/Maildir/.Pending" ) || die "Can't change to directory $TMDA_DIR/pending\n";

chomp $HostName;

while (<>)
   {
   # Search for function.
   $function = "release" if ( /tmda-release/ );
   $function = "whitelist" if ( /tmda-whitelist/ );
   $function = "get-summary" if ( /tmda-get-summary/ );
   $function = "get-whitelist" if ( /tmda-get-whitelist/ );
   $function = "get-confirmed" if ( /tmda-get-confirmed/ );
   $function = "get-blacklist" if ( /tmda-get-blacklist/ );
   $function = "get-revoked" if ( /tmda-get-revoked/ );

   if ( $function eq "get-summary" )
      {
      $command = "/usr/sbin/tmda-pending-mail \"\" $USER $HostName";
      print "$command\n";
      system "$command";
      exit( 0 );
      }

   if ( $function eq "get-whitelist" or $function eq "get-confirmed" or
        $function eq "get-blacklist" or $function eq "get-revoked" )
      {
      $function =~ s/get-//; # Chop off "get-" to find file name.
      $command = "/usr/sbin/tmda-email-maildrop $USER\@$HostName \"TMDA $function\" < $TMDA_DIR/lists/$function";
      print "$command\n";
      exit( system $command );
      }

   # Search for a file name in the subject.
   if ( /^Subject:/ )
      {
      /(\d+\.\d+)/; # Match xxx.yyy number for pending file.
      $untainted_pending_file = $1;

      # Whitelist function.
      if ( $untainted_pending_file && $function eq "whitelist" )
         {
           $command = "/usr/bin/tmda-pending -b -W $untainted_pending_file";
           print "$command\n";
           my $result = `$command 2>&1`;
           $_ = $result;
           if ( ! /whitelist/ )
           {
             error_msg( "$result\n" );
           }
           exit( 0 );
         }

      # Release function.
      if ( $untainted_pending_file && $function eq "release" )
         {
           $command = "/usr/bin/tmda-pending -b -r $untainted_pending_file";
           print "$command\n";
           my $result = `$command 2>&1`;
           $_ = $result;
           if ( ! /release/ )
           {
             error_msg( "$result\n" );
           }
           exit( 0 );
         }
      }
   }

# Leave a message in the log file but zap the mail.
print "tmda-mail-proc function: $function\n";
exit( 0 );

# Send an error message mail to the user.
sub error_msg
{
my ($msg) = @_;
my $command = "/usr/sbin/tmda-email-maildrop $USER\@$HostName \"TMDA $function\"";
open( OUT, "| $command" ) || die "Can't start $command\n";
print OUT "\n";
print OUT "$msg\n";
close( OUT );
print "$msg\n"; # Also display results in mail log file.
}
