#!/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: $nmemail\n";
    print FP "CC: $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 $applicant,\n\n".
    "Your Application Manager ($manager) is currently marked as inactive,\n".
    "as a result you have been moved into the queue of people waiting to\n".
    "be assigned an Application Manager. One will be assigned to you in\n".
    "due course.\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;

    # Move the NMs to the waiting for AM queue
    my $sql = "UPDATE applicant SET manager=NULL 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($updatesql);
    $sth->execute();

    # FIXME: write something to the log table (not sure exactly what to put there).

    # Notify 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();

