#! /usr/local/bin/perl -w
#
# Respond to email requests for complimentary tickets to an
# ApacheCon opening reception.
#
use strict;
use DBI;
use DBD::mysql;
use MIME::Parser;
use Mail::Mailer;

my $LIMIT = 150;
my $EVENT = '2002/US';
my $ename;
my $uroot;
my $msg;
my $email = $ARGV[0] || 'test';

my $parser = new MIME::Parser;
$parser->output_to_core(10000000);
$parser->output_dir('/tmp/');
eval {
    $parser->tmp_recycling(0);
};
my $entity = $parser->read(\*STDIN)
    or die("Couldn't get message from stdin!");

#
# Fine.  Figure out the email address.
#
$email = ($entity->get('Reply-to')
          || $entity->get('From')
          || $entity->get('Sender'));
chomp($email) if ($email);
if (! $email) {
    die("Couldn't figure out message origin!");
}
my @address_bits = Mail::Address->parse($email);
my $envaddr = shift(@address_bits);
$email = $envaddr->address();
$email =~ s:\@(.*):\@\L$1\E:g;

#
# Now we know who it's from, so figure out what to do.
#
my $dsn = "DBI:mysql:database=apachecon;host=Data.ApacheCon.Com";
my $dbcx = DBI->connect($dsn, 'ac2k', '');

my $sql = ('SELECT name, root '
           . 'FROM edata '
           . "WHERE (event LIKE '$EVENT') ");
my $dbquery = $dbcx->prepare($sql);
$dbquery->execute();
my $dbr = $dbquery->fetchrow_hashref();
$ename = $dbr->{'name'};
$uroot = $dbr->{'root'};
$dbquery->finish();

#
# See if we already gave them a ticket.
#
my $rid = get_rid($dbcx, "email = '$email'");
if ($rid) {
    $msg = <<EOM;
You have already requested and received a complimentary
admission ticket to the $ename opening reception.
Your ticket number is: $rid.  THIS TICKET IS FOR
YOU ALONE.  Only one person will be admitted per
ticket.

The Apache Software Foundation
EOM

    reply($email, $entity, $msg);
    $dbcx->disconnect();
    exit(0);
}

#
# No, we have no record of this eddress asking for a ticket.
#
my $last_rid = get_rid($dbcx);

if ($last_rid) {
    $last_rid =~ /COMDEX-(\d+)/;
    $last_rid = $1;
}
else {
    $last_rid = 0;
}

#
# See if we even have any more.
#
if ($last_rid >= $LIMIT) {
    $msg = <<EOM;
Thank you for requesting a complimentary ticket for
the $ename opening reception.   This is
an automated response.

Unfortunately there are no more tickets available,
but please feel free to visit our exhibit area on
Wednesday November 20 or Thursday November 21,
between 9am and 5pm.  Or take a moment to look at
our tutorial program on Monday November 18; you can
find descriptions of the tutorials on the ApacheCon
Web site at
<URL:http://ApacheCon.Com$uroot/html/sessions.html>.

The Apache Software Foundation
EOM

    reply($email, $entity, $msg);
    $dbcx->disconnect();
    exit(0);
}

#
# Okey, assign a new ticket to this eddress.
#
$last_rid++;
my $new_rid = sprintf("COMDEX-%03d", $last_rid);
$sql = ('INSERT INTO guest '
        . "SET event = '$EVENT', email = '$email', data='COMDEX', "
        . "rid = '$new_rid' ");
$dbquery = $dbcx->prepare($sql);
$dbquery->execute();

#
# Verify that the ticket is in the database..
#
$rid = get_rid($dbcx, "email = '$email'");
if (! $rid) {
    $msg = "Sorry, had trouble recording your RSVP:\n"
                . "  " . $dbcx->errstr . "\n";
    reply($email, $entity, $msg);
    $dbcx->disconnect();
    exit(0);
}

#
# Got a ticket for them; let 'em know.
#
$msg = <<EOM;
Thank you for requesting a ticket to the $ename
opening reception.  We look forward to meeting you!
This is an automated response.

Your ticket number is:

    $rid

This ticket is for you and you alone; if there are
others in your group who wish to attend, please
instruct them to each send its own message to this
service.

Please print this message and bring it with you
to the $ename registration desk to check
in on Tuesday evening.  And please take a moment
to look at our new in-depth tutorial program offered
on Monday Nov. 18. Descriptions of each tutorial 
class can be found on the ApacheCon Web site at
<URL:http://ApacheCon.Com$uroot/html/sessions.html>.

The Apache Software Foundation
EOM

reply($email, $entity, $msg);
$dbcx->disconnect();
exit(0);

sub get_rid {
    my ($dbcx, $where) = @_;

    my $sql = ('SELECT rid '
               . 'FROM guest '
               . "WHERE (event LIKE '$EVENT') "
               . 'AND (data = "COMDEX") '
               . 'AND (rid LIKE "COMDEX-%") '
               . ($where ? "AND ($where) " : '')
               . 'ORDER BY rid DESC');
    my $dbquery = $dbcx->prepare($sql);
    $dbquery->execute();
    my $dbr = $dbquery->fetchrow_hashref();
    my $rid = $dbr->{'rid'};
    $dbquery->finish();

    return $rid;
}

sub reply {
    my ($email, $entity, $msg) = @_;

    my  $subject = $entity->get('Subject');
    if ($subject) {
        chomp($subject);
        $subject =~ s/^(?:(?:Re|Sv|Aw|Antwort):\s+)*//i;
    }
    my $refs = $entity->get('References');
    my $msgid = $entity->get('Message-ID');

    my $reply = new Mail::Mailer('sendmail');
    my %header = ('Subject'        => "Re: $subject",
                  'To'             => $email,
                  'Bcc'            => 'Ken.Coar@Golux.Com',
                  'From'           => ('ApacheCon Planning Committee '
                                       . '<planners@ApacheCon.Com>'),
                  'Content-Type'   => 'text/plain',
                  'MIME-Version'   => '1.0');
    if ($msgid) {
        chomp($refs) if ($refs);
        chomp($msgid) if ($msgid);
        $refs = $msgid . ($refs ? ", $refs" : '');
        $header{'In-Reply-To'} = $msgid;
        $header{'References'}  = $refs;
    }
    $reply->open(\%header);
    print $reply $msg;
    $reply->close();
    return 1;
}
