#!/usr/bin/perl

$log = "/var/log/apache2/phpmail/mail.log";

my $timestamp = localtime ;

if ( @ARGV < 1 ) {
	print "No parameters!\n";
	exit 43;
}

$domain = @ARGV[0];

@userinput =  <STDIN>;

# $fromline = "From: noreply\@$domain\n";

$ll='';
foreach $line (@userinput) {

	if ($line =~ m/^To\:/) {
		$toline=$line;
		$ll='t';
	}
	elsif ($line =~ m/^From\:/) {
		$fromline=$line;
		$ll='f';
	}
	elsif ($ll eq 't' && $line =~ m/^[\t ].+/) {
		chomp($toline);
		$toline.=$line;
	}
	elsif ($ll eq 'f' && $line =~ m/^[\t ].+/) {
		chomp($fromline);
		$fromline.=$line;
	}
	elsif ($line =~ m/^$/) {
		last;
	}
	else {
		$ll='';
	}

}

if (($fromline =~ m/.*$domain.*/) || ($toline =~ m/.*$domain.*/)) {
	open SEND, "| /usr/bin/msmtp -t -i -fnoreply\@$domain "  or die "MSMTP failed: $!\n";
	foreach $uiline (@userinput) {
		print SEND "$uiline";
	}
	close SEND;

	chomp($fromline);
	chomp($toline);
	open LOG, ">>$log"  or die "LOG failed: $!\n";
	print LOG "$timestamp Message queued ($fromline $toline) $domain\n";
	close LOG;
}
else {
	chomp($fromline);
	chomp($toline);

	open LOG, ">>$log"  or die "LOG failed: $!\n";
	print LOG "$timestamp ERROR: Message blocked ($fromline $toline) $domain\n";
	close LOG;

	print "From: and To: domain incorrect!\n";
	exit 47;
}
