#!/usr/bin/perl

use Mail::ExpandAliases;
use File::Basename;
use POSIX qw(getgroups);

use strict;
use warnings;

sub debug {
  if (defined($ENV{'DEBATHENA_SENDMAIL_DEBUG'}) && 
      ($ENV{'DEBATHENA_SENDMAIL_DEBUG'} eq 'yes')) {
    print STDERR "DEBUG: " . join(' ', @_) . "\n";
  }
}

my $kuser;
my $want_auth = $ENV{'DEBATHENA_SENDMAIL_AUTH'} || '';

system(qw(klist -s));
if (($? == 0) &&
    (`klist 2>/dev/null` =~ /Default principal: (.*?)\@ATHENA.MIT.EDU/)) {
    $kuser = $1;
    # Remove any instances
    $kuser =~ s|/.*||g;
}

my $parser = Mail::ExpandAliases->new;

if (basename($0) eq 'newaliases') {
    my $root = join(', ', @{$parser->expand('root')});
    if ($root !~ /@/) {
	print STDERR <<EOF
NOTE: root expands to: $root
This does not appear to contain a remote address.  Since debathena-msmtp
does not support local delivery, you may wish to send root's mail
somewhere useful (e.g. your MIT account).
EOF
    }
    exit 0;
}

sub from_address {
  # If we have tickets, use them
  if ($kuser) {
    return "--from=" . join('@', $kuser, 'mit.edu');
  }
  # Note that ATHENA_USER is explicitly not checked here. We've
  # already checked to see if you have Kerberos tickets, and
  # semantically, if you don't have Kerberos tickets, you're not
  # sending as an Athena user.
  my $uname = $ENV{'USER'} || $ENV{'LOGNAME'} || getpwuid($<);
  # Otherwise, assume user@fqdn ...
  chomp(my $maildomain = `hostname --fqdn`);
  # ... except that nss-nonlocal-users are @mit.edu
  if (getgrnam('nss-nonlocal-users')) {
    my $nssnonlocalgid = (getgrnam('nss-nonlocal-users'))[2];
    if (grep(/^$nssnonlocalgid$/, getgroups())) {
      debug("Assuming \@mit.edu for nss-nonlocal-user $uname");
      $maildomain = 'mit.edu';
    }
  }
  return "--from=" . join('@', $uname, $maildomain);
}

my @aliases = ();
foreach my $arg (@ARGV) {
    push @aliases, $parser->expand($arg);
}

if ($kuser && (($want_auth eq 'yes') || ($want_auth eq '')) ) {
    #send auth
    debug(qw{msmtp --host=outgoing.mit.edu --port=587 --auth=gssapi}, "--user=$kuser", from_address(), @aliases);
    exec(qw{msmtp --host=outgoing.mit.edu --port=587 --auth=gssapi}, "--user=$kuser", from_address(), @aliases);
}
elsif ($want_auth eq 'yes') {
    $! = 1;
    die "Could not find valid ATHENA.MIT.EDU Kerberos tickets.\n";
}
else {
    #send unauth
    debug(qw{msmtp --host=outgoing.mit.edu --port=25 --auth=off}, from_address(), @aliases);
    exec(qw{msmtp --host=outgoing.mit.edu --port=25 --auth=off}, from_address(), @aliases);
}
