#!/usr/bin/perl

# use strict;
use Env;
use DBI;

######################################################################
# --CONFIGURATION

# DB access
$db_name='DBI:mysql:sendmailwrapper:localhost:3306';
$db_uid='smwrapper';
$db_pwd='yourPassword';

# full path to sendmail
$sendmail="/usr/sbin/sendmail.orig";

### debug/log level
# 0  = no logging : default
# 1+ = log current working directory and uid
# 2+ = log arguments passed : simple testing stuff
# 3+ = log article headers : reasonable, but watch file size
# 4+ = log whole article body : overkill here
$debug=1;

### throttle
# 0  = no throttle
# 1+ = throttle turend on
$throttle=1;

### needed if debug > 0
$logfile="/var/www/log/sendmail-wrapper.log";

# --end CONFIGURATION
######################################################################


$arg_str = join(' ',@ARGV,' '); # rebuild arg string
$arg_str =~ s/\s{2,}/ /g; # remove extra whitespaces
@arg_arr = split(/ /,$arg_str);

my $date = `date -R`;
chomp $date;
my $uid  = $>;
#my @info = getpwuid($uid);
my @info = $uid;
my $status = 'OK';

# throttle email
if ($throttle > 0) {
    my $datetime = `date "+%Y-%m-%d %H:%M:%S"`;
    my $dbh = DBI->connect($db_name, $db_uid, $db_pwd);
    if (!defined $dbh) { die 'Connection to database failed.'; }
    
    my $throttles = $dbh->prepare("SELECT count_max, count_cur FROM throttle WHERE orig_uid = '$uid'");
    $throttles->execute;
    if ($row = $throttles->fetchrow_arrayref) {
        $count_max = $row->[0];
        $count_cur = $row->[1];
        
        my $updateThrottle = $dbh->prepare("UPDATE throttle SET count_cur = (count_cur + 1), last_request = '$datetime' WHERE orig_uid = '$uid'");
        $updateThrottle->execute;
        if ($count_cur >= $count_max) {
            $status = 'DROPPED';
        }
    } else {
        my $insertThrottle = $dbh->prepare("INSERT INTO throttle (orig_uid, last_request) VALUES ('$uid', '$datetime')");
        $insertThrottle->execute;
    }
}

# log current working dir and uid
if ($debug >0) {
    open(LOG,">>$logfile") || 
      die "Can't append to logfile $logfile:\n $!\n";

    if ($REMOTE_ADDR) {
        print LOG "[$date] $REMOTE_ADDR ran $SCRIPT_NAME at $SERVER_NAME ($status)\n";
    } else {
        print LOG "[$date] $PWD - @info ($status)\n";
    }
}

# log arguments string
if ($debug >1) {
    printf(LOG "sendmail called using args: %s\n", $arg_str);
}

# terminate here if status is not OK
if ($status ne 'OK') {
    close(LOG) if ($debug > 0);
    die 'sendmail-throttle: mail limit reached!';
}

# write to sendmail
die "sendmail : $sendmail not executable\n" if (! -x $sendmail);
open(SMAIL, "|$sendmail @arg_arr") || 
  die "Can't intialize sendmail with: $sendmail $arg_str\n $!\n";
select(SMAIL);
$| = 1; # unbuffer sendmail file handle


# for just the article headers
while(<STDIN>) {
    printf(LOG "%s",$_) if ($debug >2);
    printf(SMAIL "%s",$_);
    last if ( /^[\n\r]$/ );
}

# and for the article body
if ($debug >3) {
    while(<STDIN>) {  
        printf(LOG "%s",$_);
        printf(SMAIL "%s",$_);
    }
} else {
    while(<STDIN>) {  
        printf(SMAIL "%s",$_);
    }
}
printf(LOG "\n") if ($debug >3);
                          

# close handles
close(SMAIL);
close(LOG) if ($debug > 0);
