#! /usr/bin/perl
# Exit 0 if email should be blocked
use strict 'vars';
$ENV{'PATH'} = "/sbin:/bin:/usr/sbin:/usr/bin";

my ($email, $to, $islist);
$to = "the EMPS email server";

open(STDERR, ">>/tmp/amstaff");
print STDERR `date`;
while (<>) {
    if (/^From:\s+(\S+)/ ) {
	print STDERR "Header: $_";
	$email = $1;
	/<(.*)>/ and $email = $1;
    }
    elsif (/^(To|Cc|Bcc):\s+(.+?)\s*$/ ) {
	$to = $2;
    }
    elsif ( /^List-/i ) {
	$islist = 1;
    }
}

if (&amstaff($email) ) {
    print STDERR "I am staff\n";
    exit(1);
}
else {
    print STDERR "I am NOT staff\n";
    &message();
    exit(0);
}

sub message {
    $islist && return;
    $email =~ /\@/ || return;
    $email =~ /[\'\s]/ && return;
    open (MAIL, "| mail -s 'Rejected: $to' '$email'");
    print MAIL "Your recent message to $to was rejected
as this lists only accepts emails from staff, associates or PhD students.

If you think this was an error please email empsit\@exeter.ac.uk

Thank you.
";
    close(MAIL);
    
}

# Return 1 for OK, 0 to bounce
sub amstaff {
    my($email) = @_;
    print STDERR "EMAIL: $email\n";

    # Temporary bounce from JMR:
#    $email =~ /rowe\b/i && return 0;

    $email =~ /@(excc|astro)\.ex\.ac\.uk$/ && return 1;
    $email =~ /\@exeter\.ac.uk$/ || return 0;

    # Anything without a digit is assumed to be staff
    $email =~ /\d/ || return 1;

    my $search = "ldapsearch  -L -x -H ldap://ldap.ex.ac.uk -b 'ou=people,dc=exeter,dc=ac,dc=uk' '(mail=$email)'";

#    print STDERR "LDAP: $search\n";
    my($cn, $mail, $uid);
    open(LDAP, "$search | ") || return;
    while(<LDAP>) {
	/exeterStatusMulti:\s+(Associate|Staff|Postgraduate)/i && return 1;
    }
    close LDAP;

    return 0;
}

