#!/usr/bin/perl

use Env;
use Getopt::Std;
use Mail::Sendmail;
# use Data::Dumper;



my $hname = `hostname`;
chomp($hname);
my $dname = `domainname`;
chomp($dname);
if ($hname ne $dname) {
	$hname .= '.' . $dname;
}
my $DEFAULT_SENDER = "pantera\@$hname";
my $DEFAULT_RECIPIENT = 'False';

getopts('f:i:');

$opt_f ||= $DEFAULT_SENDER;
$opt_i ||= $DEFAULT_RECIPIENT;


if ($opt_f =~ /^False$/ or $opt_i =~ /^False$/ ) {
	die "\n\nbiteme: $opt_f $opt_i\nusage:\n\tbody | $0 [-f from] -i to\n";
}

%mail = (	To      => $opt_i,
			From    => $opt_f,
			body	=> ''
	);

my $bs = 0;
while ($line = <STDIN>) {
	if (!$bs) {
		# try desperately to parse the inline header fields out
		# because that's the way mail::sendmail works, damnit
		if ($line =~ /^$/) {
			$bs = 1;
			next;
		}
		if ($line  =~ /^Subject: (.*)/) {
			$mail{subject} = $1;
			next;
		}
		if ($line  =~ /^Content-Length: (.*)/) {
			$mail{'Content-Length'} = $1;
			next;
		}
		if ($line  =~ /^To: .*/) {
			next;
		}
	}
	$mail{body} .= $line;
}

$mail{To} =~ /.*\@(.*)/;
$Mail::Sendmail::mailcfg{smtp} = ["mail.$1","$1"];

# $mail{body} .= Dumper(\$Mail::Sendmail::mailcfg{smtp});

# print Dumper(\%mail);

if (!sendmail(%mail)) {
	print $Mail::Sendmail::error;
	# print Dumper(\%mail);
	print "\n";
	exit 1;
}

# print "OK. Log says:\n", $Mail::Sendmail::log;
# print "\n";

# exit 0;
