#!/usr/local/bin/perl
#
# Called as 'loopcheck listname outgoing-alias' with an email message
# on standard input.
# Check for an X-Loop: listname header
# If it finds one, the message is tossed to the postmaster
# If it doesn't, the message is sent on to the outgoing-alias
#
# By Alan Schwartz, 1997
#

# Where is sendmail?
my $sendmail = "/usr/lib/sendmail";

die "Usage: loopcheck listname outgoing-alias\\n" unless @ARGV == 2;

my $listname = shift(@ARGV);
my $alias = shift(@ARGV);

# Read the message headers, checking for X-Loop: listname
$loop = 0;
while (<STDIN>) {
  push(@header,$_);
  last if /^$/;
  $loop = 1 if /^X-Loop: $listname/o;
}

if ($loop) {
  # This message is looping. We'll send it to the postmaster instead.
  open(MAIL,"|$sendmail -oi postmaster") or die "Unable to pipe to sendmail\\n";
  print MAIL <<END_OF_MESSAGE;
To: postmaster
From: Loopcheck <nobody>
Subject: Mailing list loop detected

The loopcheck program received a message for the list $listname
that already had an X-Loop: header from that list. The message
is reprinted below. It has not been distributed to the list.

@header
END_OF_MESSAGE
  print MAIL <STDIN>;
  close(MAIL);
} else {
  # The message is ok
  open(MAIL,"|$sendmail -oi $alias") or die "Unable to pipe to sendmail\\n";
  print MAIL @header;
  print MAIL <STDIN>;
  close(MAIL);
}
