#!/opt/local/bin/perl

use XML::DOM;

my $parser = new XML::DOM::Parser;

die "No gpt package file provided" if not defined @ARGV[0];

my $gptdoc = $parser->parsefile(@ARGV[0]);

my $gptmeta = $gptdoc->getElementsByTagName("gpt_package_metadata");
my $gptname = $gptmeta->item(0)->getAttributeNode("Name")->getValue;

my $gptagingver = $gptdoc->getElementsByTagName("Aging_Version");
my $gptmajorver = $gptagingver->item(0)->getAttributeNode("Major")->getValue;
my $gptminorver = $gptagingver->item(0)->getAttributeNode("Minor")->getValue;

my $description = $gptdoc->getElementsByTagName("Description")
    ->item(0)->getFirstChild->getData;

my $flavor = $gptdoc->getElementsByTagName("Flavor")
    ->item(0)->getFirstChild->getData;

my %deps;
for my $bindep ($gptdoc->getElementsByTagName("Binary_Dependencies")) {
    my $type = $bindep->getAttributeNode("Type")->getValue;
    next unless $type eq "Compile";
    for my $dep ($bindep->getElementsByTagName("Dependency")) {
        my $depname = $dep->getAttributeNode("Name")->getValue;
        $depname =~ tr/_/-/;
        my $depver = $dep->getElementsByTagName("Simple_Version")
            ->item(0)->getAttributeNode("Major")->getValue;
        $deps{$depname} = $depver;
    }
}

my $cflagselem = $gptdoc->getElementsByTagName("cflags")->item(0);
my $cflagsnode = $cflagselem->getFirstChild if defined $cflagselem;
my $cflags = $cflagsnode->getData if defined $cflagsnode;

my $extincelem = $gptdoc->getElementsByTagName("external_includes")->item(0);
my $extincnode = $extincelem->getFirstChild if defined $extincelem;
my $extinc = $extincnode->getData if defined $extincnode;

my $pkglibselem = $gptdoc->getElementsByTagName("pkg_libs")->item(0);
my $pkglibsnode = $pkglibselem->getFirstChild if defined $pkglibselem;
my $pkglibs = $pkglibsnode->getData if defined $pkglibsnode;

my $extlibselem = $gptdoc->getElementsByTagName("external_libs")->item(0);
my $extlibsnode = $extlibselem->getFirstChild if defined $extlibselem;
my $extlibs = $extlibsnode->getData if defined $extlibsnode;

my $name = $gptname;
$name =~ tr/_/-/;

$description =~ s!^\s+|\s+$!!g;
$description =~ s!\s+! !g;

my $version = $gptmajorver . '.' . $gptminorver;

my $libs = "-L\${libdir} $pkglibs $extlibs";
$libs =~ s!^\s+|\s+$!!g;
$libs =~ s!\s+! !g;

$cflags = "$cflags -I\${includedir}/globus -I\${libdir}/globus/include $extinc";
$cflags =~ s!^\s+|\s+$!!g;
$cflags =~ s!\s+! !g;

print "prefix=@ARGV[1]\n";
print "exec_prefix=\${prefix}\n";
print "libdir=\${exec_prefix}/lib\n";
print "includedir=\${prefix}/include\n";
print "\n";
print "Name: $name\n";
print "Description: Globus Toolkit - $description\n";
print "Version: $version\n";
print "Requires:";
while (($key, $value) = each(%deps)) {
    print ($value > 0 ? " $key >= $value" : " $key");
}
print "\n";
print "Libs: $libs\n";
print "Cflags: $cflags\n";
