#!/usr/athena/bin/perl
# Written by lmb@pointer.teuto.de; modified by kolya@mit.edu.
#
# This script tries to deliver bang-path email.
#

$LOCAL = $ENV{"LOCAL"};

exit 100 unless $LOCAL =~ /\!/o;
exit 100 unless $LOCAL =~ /^[\w\d\-\_\.\!]+$/;
exit 100 if ($LOCAL =~ /\!\!/ or $LOCAL =~ /^\!/ or $LOCAL =~ /\!$/);
if ($LOCAL =~ /orbs-relaytest/ and $LOCAL =~ /manawatu\.co\.nz/) {
  print "Relaying not permitted.\n";
  exit 100;
}

$SENDER = $ENV{"SENDER"};
if ($SENDER eq "sender\@orbs.org" or $SENDER eq "sender\@imrss.org") {
  print "Relaying not permitted.\n";
  exit 100;
}

($SYSTEM_TO,$USER_TO) = $LOCAL =~ /^([^!]+)\!(\S+)/o;

%UUCP_NEIGHBORS = (
# bu.edu seems to block UUCP messages with an anti-relaying filter
# relay their messages via world.std.com instead
#	'bu.edu',	'bu.edu',
	'bu.edu',	'world.std.com',

# mit-athena is likely to relay all messages to addresses containing '!'
# back to bloom-beacon; try world.std.com instead (only node wgbh?)
#	'mit-athena',	'athena.mit.edu',
	'mit-athena',	'world.std.com',

	'mit-eddie',	'eddie.mit.edu',

# anti-relaying filter: use world.std.com instead
#	'spdcc',	'spdcc.com',
	'spdcc',	'world.std.com',

# anti-relaying filter: use eddie.mit.edu instead
#	'think',	'think.com',
	'think',	'eddie.mit.edu',

	'world',	'world.std.com',

	'incommunicado','incommunicado.ihtfp.org',
	);

($SYSTEM_TO_AGAIN, $PATH) = split(/\s+/,
		`grep $SYSTEM_TO /var/qmail/uucp/alpath | grep -w $SYSTEM_TO`);

if ($PATH eq '') {
  print "No path to destination node $SYSTEM_TO.\n";
  exit 100;
}

($RELAY_NODE, @RELAY_PATH) = split(/\!/, $PATH);

if ($RELAY_NODE eq '') {
  print "No next hop for path to $SYSTEM_TO.\n";
  exit 100;
}

if ($RELAY_NODE eq '%s') {
  # This is mail for our system.. Deliver it as such
  $NEW_TO=$USER_TO;
} else {
  # Find the path to the next hop system
  if ($UUCP_NEIGHBORS{$RELAY_NODE} eq '') {
    print "Missing destination for next hop $RELAY_NODE to $SYSTEM_TO.\n";
    exit 100;
  }

  $RELAY_PATH_TMPL=join('!', @RELAY_PATH);
  $RELAY_PATH=sprintf($RELAY_PATH_TMPL, $USER_TO);
  $NEW_TO = "$RELAY_PATH\@".$UUCP_NEIGHBORS{$RELAY_NODE};
}

system("/var/qmail/bin/qmail-inject -a $NEW_TO");

exit 99;
