#!/usr/bin/env perl

use strict;
use FileHandle;
use POSIX;

# Config stuff
#
# Modules that should be pulled out of the host record
# BENC: do we need to do that?

# TODO: timestamps should not be OGSI


my %services = (condor => sub { &get_ad("condor_NumMasters", $_[0]) > 0 },
		gdmp => sub { &get_ad("gdmp_last_heartbeat_received", $_[0]) });

# Get the base status
my $condor_status = $ENV{'GLOBUS_SH_CONDOR_STATUS'};
if ($condor_status eq "")
{
    $condor_status = "condor_status";
}

my $args = join " ", @ARGV;
my $xml = `$condor_status $args -xml`;

# Split into individual VM records
my @xml = split /<\/c>/, $xml;
pop @xml;

# Get the classad lifetime (availableUntil)
my $lifetime = 900;
my $last_heard = &get_ad("LastHeardFrom", $xml);
my $available_until = $last_heard + $lifetime;
$available_until = &get_time_string($available_until);
my $up;

# Find all valid hawkeye prefixes (based on <prefix>_LastUpdate) in the
# whole XML document...

my %prefixes = map { /a n=\"(.+)_LastUpdate/; $1 => 1 } 
    grep /_LastUpdate/, split /\n/, $xml;



# XML wrapper

my $clusterid = "pool";

my $new_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
#$new_xml .= "<ClusterInformation xmlns=\"http://mds.globus.org/glue/ce/1.1\" >\n";
$new_xml .= "<glue:ClusterInformation xmlns:glue=\"http://mds.globus.org/glue/ce/1.1\" xmlns:sched=\"http://mds.globus.org/batchproviders/2004/09\">";
$new_xml .= "<glue:Cluster glue:Name=\"$clusterid\" glue:UniqueID=\"$clusterid\">\n";
$new_xml .= "<glue:SubCluster glue:Name=\"$clusterid\" glue:UniqueID=\"$clusterid\">\n";

# for each classad
foreach my $xml (@xml)
{
    # Figure out the vm name and start the record
    my $name = &get_ad("Name", $xml);


#    # First add service modules
#    foreach my $prefix (keys %services)
#    {
#	next unless $prefixes{$prefix};
#	delete $prefixes{$prefix};
#	
#        # Pull out goodFrom and goodUntil
#	my $good_from = &get_ad("${prefix}_LastUpdate", $xml);
#        my $good_until = &get_ad("${prefix}_NextUpdate", $xml);
#
#        # We don't always know good_until, thanks to waitforexit modules
#        $good_until ||= $good_from + 60*60*24;
#
#        # Format time strings
#        $good_from = &get_time_string($good_from);
#        $good_until = &get_time_string($good_until);
#
#        # Figure out up/down
#        $up = $services{$prefix}($xml);
#        if ($up)
#        {
#            $up = "UP";
#        }
#        elsif (defined($up))
#        {
#            $up = "DOWN";
#        }
#        else
#        {
#            $up = "UNDEFINED";
#        }
#
#        # Add to the XML
#        $new_xml .= "<test ogsi:goodFrom=\"$good_from\" ogsi:goodUntil=\"$good_until\" ogsi:availableUntil=\"$available_until\" xmlns:ogsi=\"http://www.gridforum.org/namespaces/2003/03/OGSI\">\n";
#        $new_xml .= "  <reporter><name>$0 (top)</name></reporter>\n";
#        $new_xml .= "  <target><url>$name/$prefix</url><name>Condor</name></target>\n";
#        $new_xml .= "  <result><status>$up</status>\n";
#	$new_xml .= "    <comment>\n";
#        $new_xml .= "    <classad>\n";
#	$new_xml .= $xml;
#
##	$new_xml .= join "\n", grep !/(Next|Last)Update/, 
##            grep /a n=\"${prefix}_/, split /\n/, $xml;
#
#        $new_xml .= "    </classad>\n";
#
#        my $dollar = "\$";
#        $new_xml .= "<providerVersion>\$Id: hawkeye_glue.pl,v 1.11.2.2 2006/06/23 19:53:52 mdarcy Exp $dollar    </providerVersion>\n";
#	$new_xml .= "\n    </comment>\n";    
#	$new_xml .= "</result>";    
#        $new_xml .= "\n</test>\n";
#    }
    
    # Add the host record
    #
    # Find the smallest availableUntil
    my $from_min = time+60*60*24;
    my $until_min = time+60*60*24;
    foreach my $prefix (keys %prefixes)
    {
        # Pull out goodFrom and goodUntil
	my ($good_from) = &get_ad("${prefix}_LastUpdate", $xml);
        my ($good_until) = &get_ad("${prefix}_NextUpdate", $xml);

        # We don't always know good_until, thanks to waitforexit modules
        $good_until ||= $good_from + 60*60*24;
	
	next unless $good_until < $until_min;
	
	$from_min = $good_from;
	$until_min = $good_until;
    }

    # Make them into strings
    my $status = $up;
    $from_min = &get_time_string($from_min);
    $until_min = &get_time_string($until_min);

#    $new_xml .= "<test ogsi:goodFrom=\"$from_min\" ogsi:goodUntil=\"$until_min\" ogsi:availableUntil=\"$available_until\" xmlns:ogsi=\"http://www.gridforum.org/namespaces/2003/03/OGSI\">\n";
#    $new_xml .= "  <reporter><name>$0</name></reporter>\n";
#    $new_xml .= "  <target><url>$name</url><name>Hawkeye on $name</name></target>\n";
#    $new_xml .= "  <result><status>$status</status>\n";
#    $new_xml .= "    <comment>\n";

    $new_xml .= make_glue_xml($xml);

	
#    $new_xml .= "    <classad>\n";

#    foreach my $prefix (keys %prefixes)
#    {
#        $new_xml .= join "\n", grep !/(Next|Last)Update/, 
#            grep /a n=\"${prefix}_/, split /\n/, $xml;
#    }
#    $new_xml .= $xml;
#    $new_xml .= "    </classad>\n";
    my $dollar = "\$";
#    $new_xml .= "<providerVersion>\$Id: hawkeye_glue.pl,v 1.11.2.2 2006/06/23 19:53:52 mdarcy Exp $dollar    </providerVersion>\n";

#    $new_xml .= "\n    </comment>\n";
#    $new_xml .= "</result>\n";
#    $new_xml .= "</test>\n";
}
#$new_xml .= "</hawkeye>\n";
$new_xml .= "</glue:SubCluster>\n";
$new_xml .= "</glue:Cluster>\n";
$new_xml .= "</glue:ClusterInformation>\n";

# Print it out
print $new_xml;

# Get a properly formatted time string
sub get_time_string
{
    my ($time) = @_;
    
    my @utc = gmtime($time);
    $utc[5] += 1900;

    return sprintf("%04d-%02d-%02dT%02d:%02d:%02d.000", 
		   @utc[5, 4, 3, 2, 1, 0]);
}

sub emit_proper_numeric
{
    my($number) = @_;

    if ($number =~ /\D/)
    {
        $number = 0;
    }
    return $number;
}

sub emit_proper_string
{
    my($str) = @_;
    my($len) = length($str);

    if ($len < 1)
    {
        $str = "unknown";
    }
    return $str;
}

# Fetch an ad value
#
# Require quotes in the ad search for an exact match to avoid grep
# returning incorrect values (e.g. 'VirtualMemory' when looking for
# the ad called 'Memory')
sub get_ad
{
    my ($ad, $xml) = @_;

    my ($line) = grep /\"$ad\"/, split /\n/, $xml;
    if ($line =~ /<i>(\d+)/)
    {
	return $1;
    }
    elsif ($line =~ /<r>([^<]+)/)
    {
	return $1;
    }
    elsif ($line =~ /<s>([^<]+)/)
    {
	return $1;
    }
    elsif ($line =~ /<b v=\"(.)/)
    {
	return $1 eq "t";
    }
}


# TODO need to not output elements/attributes if we don't have 
# the classad info for them (bug 2148)

# This outputs the XML for a GLUE <Host>
sub make_glue_xml
{
    my ($xml) = @_;
    my $new_xml = "";

    # TODO should pull out Machine attribute here instead?
    my $hostid = &get_ad("Name",$xml);

    # vm<n>@host handling
    # These look like:
    #       <a n="Name"><s>vm1@birdie.isi.edu</s></a>

    if ($hostid =~ /^vm1@/)   # is it vm1?
    {
        $hostid =~ s/^vm1@// 
    } 
    elsif ($hostid =~ /^vm[0123456789]+@/)    #  or is it another vm?
    {
        return;
    }

    $hostid = emit_proper_string($hostid);
    $new_xml .= "<glue:Host glue:Name=\"$hostid\" glue:UniqueID=\"$hostid\">\n";

#smp load

    $new_xml .= "<glue:SMPLoad ";

    my $TotalLoadAvg = &get_ad("TotalLoadAvg", $xml);
    $TotalLoadAvg = POSIX::ceil($TotalLoadAvg * 100);
    $TotalLoadAvg = emit_proper_numeric($TotalLoadAvg);
    $new_xml .= "glue:Last1Min=\"$TotalLoadAvg\" ";
    $new_xml .= "glue:Last5Min=\"$TotalLoadAvg\" ";
    $new_xml .= "glue:Last15Min=\"$TotalLoadAvg\" ";

    $new_xml .= "/>\n";

#processor load

    $new_xml .= "<glue:ProcessorLoad ";

    my $LoadAvg = &get_ad("LoadAvg", $xml);
    $LoadAvg = POSIX::ceil($LoadAvg * 100);
    $LoadAvg = emit_proper_numeric($LoadAvg);
    $new_xml .= "glue:Last1Min=\"$LoadAvg\" ";
    $new_xml .= "glue:Last5Min=\"$LoadAvg\" ";
    $new_xml .= "glue:Last15Min=\"$LoadAvg\" ";

    $new_xml .= "/>\n";

#filesystem

    $new_xml .= "<glue:FileSystem Root=\"/\" Name=\"entire-system\" ";

    my $Size = &get_ad("TotalDisk", $xml);
    my $Disk = &get_ad("Disk", $xml);

    $Size >>= 10;
    $Disk >>= 10;

    $Size = emit_proper_numeric($Size);
    $new_xml .= "glue:Size=\"$Size\" ";

#    my $AvailableSpace = $Size - $Disk;
#    $AvailableSpace = emit_proper_numeric($AvailableSpace);
#    $new_xml .= "glue:AvailableSpace=\"$AvailableSpace\" ";

    $new_xml .= "glue:ReadOnly=\"false\" ";

    $new_xml .= "/>\n";

#benchmark
# we won't publish any benchmark info

#Processor

    $new_xml .= "<glue:Processor ";

    my $Vendor = &get_ad("Arch", $xml);
    $Vendor = emit_proper_string($Vendor);
    $new_xml .= "glue:Vendor=\"$Vendor\" ";

    my $ClockSpeed = &get_ad("Mips", $xml);
    $ClockSpeed = emit_proper_numeric($ClockSpeed);
    $new_xml .= "glue:ClockSpeed=\"$ClockSpeed\" ";

    $new_xml .= "/>\n";

# ---- MainMemory ----

    $new_xml .= "<glue:MainMemory ";

    my $RAMSize = &get_ad("Memory", $xml);
    $RAMSize = emit_proper_numeric($RAMSize);
    $new_xml .= "glue:RAMSize=\"$RAMSize\" ";

    my $VirtualSize = &get_ad("TotalVirtualMemory", $xml);
    $VirtualSize >>= 10;
    $VirtualSize = emit_proper_numeric($VirtualSize);
    $new_xml .= "glue:VirtualSize=\"$VirtualSize\" ";

    my $VirtualAvailable = $VirtualSize - $RAMSize;
    $VirtualAvailable = emit_proper_numeric($VirtualAvailable);
    $new_xml .= "glue:VirtualAvailable=\"$VirtualAvailable\" ";

    $new_xml .= "/>\n";

#OperatingSystem
# TODO split out OpSys value in name/version/release info based on
# some lookup table? What does the schema say about these values?
    my $OperatingSystem = &get_ad("OpSys",$xml);
    my $Release = &get_ad("CondorPlatform",$xml);
    $Release =~ s/\$CondorPlatform\: //;
    $Release =~ s/ \$//;
    $OperatingSystem = emit_proper_string($OperatingSystem);
    $Release = emit_proper_string($Release);
    $new_xml .= "<glue:OperatingSystem glue:Name=\"$OperatingSystem\" ";
    $new_xml .= "glue:Release=\"$Release\" />\n";

#StorageDevice
#NetworkAdapter

#    my $netix = &get_ad("net_INDEX",$xml);
#    foreach my $netname (split(' ',$netix))
#    {
#        $new_xml .= "<NetworkAdapter Name=\"$netname\" \n";

#	my $MTU = &get_ad("net_${netname}_MTU", $xml);
#	if(! ("$MTU" eq "")) { $new_xml .= "  MTU=\"$MTU\" \n "; }

#        $new_xml .= "/>\n";
	
#    }

    $new_xml .= "<glue:NetworkAdapter ";

    my $NetName = &get_ad("Machine", $xml);
    $NetName = emit_proper_string($NetName);
    $new_xml .= "glue:Name=\"$NetName\" ";

    my ($IPAddr, $port) = split /:/, &get_ad("MyAddress", $xml);
    $IPAddr =~ s/\&lt\;//;
    $IPAddr = emit_proper_string($IPAddr);
    $new_xml .= "glue:IPAddress=\"$IPAddr\" ";

    $new_xml .= "glue:OutboundIP=\"true\" glue:InboundIP=\"true\" ";

    $new_xml .= "/>\n";


#architecture
#TODO: need to map arch names to something else?

    my $archname = &get_ad("Arch", $xml);
    $archname = emit_proper_string($archname);
    $new_xml .= "<glue:Architecture PlatformType=\"$archname\" ";

    my $smpsize = &get_ad("TotalVirtualMachines", $xml);
    $smpsize = emit_proper_string($smpsize);
    $new_xml .= "glue:SMPSize=\"$smpsize\" ";

    $new_xml .= "/> \n";

#application software

    $new_xml .= "<glue:ApplicationSoftware ";

    my $CondorVersion = &get_ad("CondorVersion", $xml);
    $CondorVersion =~ s/\$//;
    $CondorVersion =~ s/ \$//;
    $CondorVersion = emit_proper_string($CondorVersion);
    $new_xml .= "glue:Name=\"$CondorVersion\" ";

    $new_xml .= "/>\n";

    $new_xml .= "</glue:Host>\n";

}

