#!/usr/local/bin/perl

$ENV{"ORGANIZATION"} = "The Internet";

if ($ARGV[0] =~ /-m/) {
    $moderated = 1;
    shift;
}
die "Not enuf args" unless ($ng = $ARGV[0]);
die "Not enuf args" unless ($dist = $ARGV[1]);
shift;shift;
$inews = "/usr/lib/news/sinews";
die "Where's inews?" unless (-x $inews);

# should lock this file, but it's just a log ...
open(LOG,">>/usr/lib/news/digests/postlog") || die "Can't open log";
print LOG "\n";

$header = 1;
while (<>) {
    print LOG $_;
    if ($header) {
	chop;
	if (/^$/) {
	    $header = 0;
	    $first_line = 1;
	    if (!$from) {
		print LOG "\n";
		die "No From:";
	    }
	} elsif (!$from && /^From\s+(\S+)/) {
	    $from = $1;
	} elsif (/^From:\s*(\S.*)/i) {
	    $from = $1;

	    # this is a hack to hold possible bounced digests in the queue
	    # to await human examination.
	    
	    $_ = $from;
	    if (/postmaster/i || /^uucp/i || /mail_3_server/i ||
		    /dead-flames/i || /ansp\.br/i) {
		print LOG "\n";
		exit 1;
	    }
	} elsif (/^Reply-To:\s*(\S.*)/i) {
	    $rp = $1;
	} elsif (/^Subject:\s*(\S.*)/i) {
	    $subj = $1;

	    # this is a hack to hold possible bounced digests in the queue
	    # to await human examination.
	    
	    #$_ = $ng;
	    #if (/gdead/ || /perl/) {
		#$_ = $subj;
		#if (/undeliverable/i || /failed/i || /uucp/i) {
		#if (/undeliverable/i || /failed/i || /warning/i) {
		#if (/undeliverable/i || /warning/i || /uucp/i) {
		#if (/undeliverable/i || /failed/i || /warning/i || /uucp/i) {
		#    print LOG "\n";
		#    exit 1;
		#}
	    #}
	}

    } elsif ($first_line) {

	# this is for the folks at rohvm1.bitnet, whose subj headers
	# always say "BITNET Mail Enclosed" or somesuch.

	$first_line = 0;
	if (/^Subject:\s*(\S.*)/i) {
	    $dont_print = 1;
	    $subj = $1;
	} elsif (!$subj) {
	    $subj = "(none)";
	}

	if (!$rp) {
	    $rp = $from;
	    $rp =~ s/[^<]*<([^>]*)>.*/$1/;
	}

	# and this is for the folks at data general, whose messages
	# always start with "CEO summary:"

	$dont_print = 1 if (/^CEO summary:/);

	open(INEWS,"|-") || exec "$inews",'-h','-n',"$ng",'-d',"$dist";

	if ($moderated) {
	    print INEWS "Approved: postmaster@Virginia.EDU\n";
	}
	print INEWS "From: $from\nSubject: $subj\nReply-To: $rp\n\n";

	if (!$dont_print) {
	    s/^>/|/;
	    print INEWS "$_";
	}

    } else {
	s/^>/|/;
	print INEWS "$_";
    }
}

close(INEWS);

if ($error) {
    $error = $? >> 8;
    printf LOG "ERROR: %s\n",$!;
}

print LOG "\n";
close(LOG);

exit $error;
