#! /usr/bin/perl
# Portions of this file Copyright 1999-2005 University of Chicago
# Portions of this file Copyright 1999-2005 The University of Southern California.
#
# This file or a portion of this file is licensed under the
# terms of the Globus Toolkit Public License, found at
# http://www.globus.org/toolkit/download/license.html.
# If you redistribute this file, with or without
# modifications, you must include this notice in the file.
#

# merge-package-metadata.pl
# This script will take as arguments a package metadata file, the
# template pkgdata file, and an output file path.
# The metadata file and the template metadata will be parsed and the
# source dependencies will be merged into the output file.
BEGIN
{
    if (exists $ENV{GPT_LOCATION}) {
        push(@INC, $ENV{GPT_LOCATION}.'/lib/perl');
    } elsif (exists $ENV{GLOBUS_LOCATION}) {
        push(@INC, $ENV{GLOBUS_LOCATION}.'/lib/perl');
    }
}

use Grid::GPT::PackageFactory;
use Data::Dumper;

my $package_factory = new Grid::GPT::PackageFactory();
my $debug = 0;

my $user_metadata_file = $ARGV[0];
my $template_file = $ARGV[1];
my $package_output_file = $ARGV[2];

if ($ARGV[0] eq '-help') {
    print "Usage: $0 pkg-metadata-file template-metadata-file output-file\n";
    exit 1;
}

my $user_package = $package_factory->type_of_package($user_metadata_file);
$user_package->read_metadata_file($user_metadata_file);
my $user_source_deps = $user_package->{Source_Dependencies};

my $template_package = $package_factory->type_of_package($template_file);
$template_package->read_metadata_file($template_file);
my $template_source_deps = $template_package->{Source_Dependencies};

print Dumper($template_source_deps) . "\n" if $debug;

foreach my $dtype (keys %{$user_source_deps->{'deptype-list'}}) {
    print STDERR "$user_metadata_file has $dtype dependencies\n" if $debug;

    foreach my $deps ($user_source_deps->query(deptype => $dtype)) {
        foreach my $dep (@{$deps}) {
            #print "In particular: " . Dumper($dep) . "\n";
            $template_source_deps->add_dependency(dep => $dep->{depnode});
        }
    }
}
print STDERR "-----------------------\n" if $debug;
print STDERR Dumper ($template_source_deps) . "\n" if $debug;

$template_package->output_metadata_file("$package_output_file");
