#!/usr/bin/perl

use DBI;
use Mail::Send;

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

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

# send report to administrator
$recipient='hostmaster@yourdomain.com';

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


my $dbh = DBI->connect($db_name, $db_uid, $db_pwd);
if (!defined $dbh) { die 'Connection to database failed.'; }

my @reports;
$select = $dbh->prepare("SELECT orig_uid, count_max, count_cur, last_request FROM throttle WHERE count_cur > count_max AND reported = 0");
if (!defined $select) { die 'prepare MySQL statement failed.'; }
$select->execute;
while ($row = $select->fetchrow_arrayref) {
    $origUid     = $row->[0];
    $countMax    = $row->[1];
    $countCur    = $row->[2];
    $lastRequest = $row->[3];
    
    push @reports, "$origUid ($countCur/$countMax) - $lastRequest";
}

# report UIDs that have reached their sender limit
if (@reports) {
    $message = "The following UID's have reached their sender limit:\r\n";
    $message .= "\r\n";
    foreach(@reports) {
        $message .= "$_\r\n";
    }

    $msg = Mail::Send->new();
    $msg->to($recipient);
    $msg->subject('Mail limit reached');
    my $fh = $msg->open('sendmail') || die $!;
    print $fh $message;
    $fh->close() || die $!;

    # set report flag to avoid double reporting
    $update = $dbh->prepare("UPDATE throttle SET reported = 1 WHERE count_cur > count_max AND reported = 0");
    $update->execute;
}
