#!/usr/bin/perl -w
# David Busby - Edoceo, Inc.

use strict;
use Data::Dumper;
use Net::SMTP;
use Net::DNS;

# Tell me who root is
use constant ROOT_IS => 'your_email@your_domain.tld';
# Supposed to be for retry count, not implemented
use constant C_RETRY => 0;
# You've seen something like this before
use constant DEBUG => 0;

$!=1;

# Do you want to log what happens?
open (STDOUT,'>>/tmp/sendmail.log');
open (STDERR,'>&STDOUT');

my $buf = do { local ($/); <STDIN>; };

my %cfg;
my $cmdline = join(' ',@ARGV);
if (DEBUG) { print "CMDLINE: $cmdline\n"; }
# BUG?: This only takes simple email addresses, not fancy ones
if ($cmdline =~ m/-f *([\w\.]+@[\w\-\.]+)/o) { $cfg{sender} = $1; }
if ($cmdline =~ m/-F *(\w+)/o) { $cfg{full_name} = $1; }

# Parse To Address Header
my $to = '';
if ($buf =~ m/To: (.+)/)
{
  if ($1 eq 'root') { $to = ROOT_IS; }
  else { $to = $1; }
}
if (DEBUG) { print "TO: $to\n"; }
if (!$to) { print STDERR "FATAL: No `To:` address specified\n"; exit(1); }
my ($user,$host) = $to =~ m/(.+)@(.+)/;

# My Hostname
my $host_name = do { my $x = `/bin/hostname -f`; chomp($x); $x; };
my $domain_name = do { my $x = `/bin/hostname -d`; chomp($x); $x; };

# Resolve name
my $res = Net::DNS::Resolver->new(debug => DEBUG);
my @mx = mx($res,$host);
if (@mx)
{
  foreach my $rr (@mx)
  {
    if (DEBUG) { print "MX: ".$rr->preference.' '.$rr->exchange."\n"; }
    # Send
    # BUG: No error checking or recovery
    my $smtp = Net::SMTP->new($rr->exchange, Hello => $host_name, Debug => DEBUG);
    $smtp->mail('cron@'.$domain_name);
    $smtp->to($to);
    $smtp->data($buf);
    $smtp->quit();
    last;
  }
}
else
{
  if (DEBUG) { print "No MX for $host\n"; }
}
exit(0);
