#!/usr/bin/perl
# $Id: rfax.pl,v 1.1 1994/06/14 11:55:46 agl Exp agl $
# /usr/local/bin/rfaxpgp
push(@INC,"/usr/local/lib/apc"); require("alib.pl");

$spooldir="$faxdir/$ARGV[0]";

sub aexit {
    unlink($signed, $postpgp, $justbody);
    ($status)=@_;
    exit $status;
}
sub sighupper {
    &aexit(0);
}
$SIG{'HUP'}="sighupper";
open(ABORT, ">/dev/console") ||
    system("echo 'rfax.pl: Can't open /dev/console!'|smail root");

if( chdir($spooldir) != 1)
{
    print ABORT "--ERROR-- rfax.pl: can't cd to $spooldir.\n";
    &aexit(-1);
}
if( !(-r "pubring.pgp") ) {
    print ABORT "--ERROR-- rfax.pl: can't access $spooldir/pubring.pgp.\n";
    &aexit(-1);
}
$signed ="/tmp/$postpgp.asc";

if(!open(SIGNED, ">$signed")) {
print ABORT "--ERROR-- rfax.pl: can't open $spooldir/SIGNED for writing.\n";
    &aexit(-1);
}
while(<STDIN>) {
    print SIGNED;
}
close(SIGNED);
if (system ($pgp, $signed, $postpgp))
{
#    unlink($signed);
    print ABORT "
--ERROR-- rfax.pl: pgp authentication FAILED on file $signed.
";
    &aexit(-1);
}
if(!open(POSTPGP, "<$postpgp")) {
print ABORT "--ERROR-- rfax.pl: can't open $spooldir/POSTPGP for writing.\n";
    &aexit(-1);
}
while(<POSTPGP>)
{
    goto parse if /^To\s*:\s*(.*)$/i;
    goto parse if /^Cc\s*:\s*(.*)$/i;
    goto parse if /^Bcc\s*:\s*(.*)$/i;
    $from=$1   if /^From\s*:\s*(.*)$/i;
    $subject=$1 if /^Subject\s*:\s*(.*)$/i;
    last if /^$/;
    next;
  parse:;
#    $ST =~ s/\D//g;
    foreach(split(/[\t ,]+/,$1)) { $_ =~ s/\D//g; next if /^$/;
				   push(@faxes, $_);
    }
}
if(!open(JUSTBODY, ">$justbody")) {
    print ABORT "--ERROR-- rfax.pl: can't open file JUSTBODY for writing.\n";
    &aexit(-1);
}
print JUSTBODY "Subject: $subject" if($subject);
print JUSTBODY "From: $from" if($from);
while(<POSTPGP>) { print JUSTBODY; }
close(POSTPGP);
close(JUSTBODY);
if(!$from)
{
    print ABORT "--ERROR-- rfax.pl: From: is NOT found\n";
    &aexit(-1);
}
#if($faxes<1)
#{
#    print ABORT "--WARNING-- rfax.pl: no job, quit\n";
#    &aexit(0);
#}
foreach(@faxes) {
    if( system("$faxer -f $from $_ <$justbody") )
    {
	print ABORT "--ERROR-- rfax.pl: Failed to execute $faxer\n";
	&aexit(-1);
    }
}
&aexit(0);
# EOF rfax.pl
