#!/usr/bin/perl

#use strict;
use DBI;
use POSIX qw(strftime);
use vars qw($enable_email);

my $DBNAME="newmaint";
my $DBUSER="nm";
$enable_email = 0;

sub send_email(@)
{
    my ($nmemail, $amemail, $body, $subject) = @_;

    open (FP, "| /usr/lib/sendmail -t") or die "Cannot open to sendmail $!";
    print FP "To: $amemail\n";
    print FP "CC: $nmemail, new-maintainer\@debian.org\n";
    print FP "From: Debian New Maintainer <new-maintainer\@debian.org>\r\n";
    print FP "Errors-To: new-maintainer\@debian.org\r\n";
    print FP "Content-Type: text/plain; charset=utf-8\r\n";
    print FP "Subject: $subject\n\n";
    print FP $body;
    close FP;
}

sub notify_am(@)
{
    my ($applicant, $nmemail, $manager, $amemail) = @_;

    my $body = "Dear $manager,\n\n".
    "This is a short reminder that one of your NM Applicants ($applicant)\n".
    "has been on hold for more than 6 months. We suggest that such applicants\n".
    "should be soft-rejected and apply again once they have more time to for\n".
    "the New Maintainer process. Please consider doing this.\n".
    "  - New Maintainer Committee\n";

    send_email($nmemail, $amemail, $body, "Warning about Debian New Maintainer Applicant");
}

sub handle_slow_ams($)
{
    my ($dbh) = @_;
    my ($applicant, $nmemail, $manager, $amemail);
    my $sth;

    # Notify AMs (and their NMs)
    if ($main::enable_email != 0) {
        my $sql = "SELECT a.forename || a.surname, a.email, a.manager, m.email FROM applicant a, manager m WHERE a.approved = 'f' and CURRENT_TIMESTAMP - a.decision > '6 months' AND a.manager == m.login";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $sth->bind_columns(\$applicant, \$nmemail, \$manager, \$amemail);
        while($sth->fetch()) {
            notify_am($applicant, $nmemail, $manager, $amemail);
        }
    }
}

my $dbh = DBI->connect("dbi:Pg:dbname=$DBNAME", $DBUSER, "");

if ($ARGV[0] eq '--email') { $enable_email = 1; }
#print $enable_email;
handle_slow_ams($dbh);
$dbh->disconnect();

