#!/s/perl-5.8.4/bin/perl

use strict;
use lib "/u/n/m/nmueller/lib";
use lib "/p/vdt/workspace/mysql/perl-5.8";
$ENV{LD_LIBRARY_PATH} = "/p/vdt/workspace/mysql/lib/mysql";

use DBI;
use CGI ":standard";
use XML::RSS (version => 2.0);

my $rss = new XML::RSS;
$rss->channel(title => "UW-Madison NMI Build/Test Results",
	      link => "http://nmi-s005.cs.wisc.edu/nmi/index.php?page=results/overview",
	      description => "This is where all the build and test run status information can be found.");
$rss->image(title => "Goofy NMI Logo",
	    url => "http://www.nsf-middleware.org/documentation/NMI-R5/0/images/header_doc_left.gif",
	    link => "http://www.nsf-middleware.org");

# Build up a query
my @query = ("1 = 1");
my @bind;
foreach my $param (param)
{
    my @subquery;
    foreach my $value (split /,/, param($param))
    {
	push @subquery, "$param = ?";
	push @bind, $value;
    }
    push @query, "(" . join(" or ", @subquery) . ")";
}
my $query = join " and ", @query;

my $dbh = DBI->connect("dbi:mysql:database=nmi_history;host=nmi-build25.cs.wisc.edu",
                       "nmipublic", "nmiReadOnly!");
my $q = $dbh->prepare("select * from Run where $query order by start desc limit 10");
$q->execute(@bind);

while (my $row = $q->fetchrow_hashref)
{
    my $result;
    if (!defined $row->{result})
    {
	$result = "running";
    }
    elsif ($row->{result})
    {
	$result = "failed";
    }
    else
    {
	$result = "succeeded";
    }
    
    my @failed = map { "$_->[0]\@$_->[1]" }
                       @{$dbh->selectall_arrayref("select name,
                       platform from Task where runid = $row->{runid}
                       and result > 0")};
    my @ip = map { "$_->[0]\@$_->[1]" }
                       @{$dbh->selectall_arrayref("select name,
                       platform from Task where runid = $row->{runid}
                       and result is null")};
    my $description;
    if (@ip)
    {
	$description .= "Tasks in progress: " . join(", ", @ip) . "\n";
    }
    if (@failed)
    {
	$description .= "Failed tasks: " . join(", ", @failed) . "\n";
    }
    if (!$description)
    {
	$description = "Run successful";
    }

    if (lc($row->{description}) eq lc($row->{component}))
    {
	$row->{description} = "";
    }
    elsif ($row->{description})
    {
	$row->{description} = "($row->{description})";
    }

    $rss->add_item(title => "$result / $row->{runid} / $row->{user} / $row->{run_type} / $row->{project} / $row->{component} $row->{description}",
		   link => "http://nmi-s005.cs.wisc.edu/nmi/index.php?page=results/runDetails&runid=$row->{runid}",
		   description => $description,
		   guid => $row->{runid});
}

$rss->textinput(title => "Search by runid",
		description => "View results for an additional runid",
		name => "runid",
		link => "http://nmi-s005.cs.wisc.edu/nmi/index.php?page=results/overview");

print "Content-type: text/xml\n\n";
print $rss->as_string;

