#!/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: front-desk@nm.debian.org\n";
    print FP "CC: $nmemail, $amemail, 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_nm(@)
{
    my ($applicant, $nmemail, $manager, $amemail) = @_;

    my $body = "Dear Front Desk,\n\n".
    "$manager is currently marked as inactive, but is assigned to $applicant.\n".
    "It is suggested that $applicant should be moved to the queue of people\n".
    "that are waiting for an AM and recieve priority in getting a new AM.\n".
    "  - New Maintainer Committee\n";

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

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

    # Notify FD, NMs and inactive application managers
    if ($main::enable_email != 0) {
        my $sql = "SELECT a.forename || a.surname, a.email, m.login, m.email FROM applicant a, manager m WHERE (a.approved = 'f' OR a.approved IS NULL) AND a.manager = m.login AND m.is_active = 'f'";
        $sth = $dbh->prepare($sql);
        $sth->execute();
        $sth->bind_columns(\$applicant, \$nmemail, \$manager, \$amemail);
        while($sth->fetch()) {
            notify_nm($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_inactive_ams($dbh);
$dbh->disconnect();

