#! /usr/bin/env perl

# 
# Copyright 1999-2006 University of Chicago
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
# http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 


=head1 NAME

B<globus_build_doxygen_dependencies> - Returns a list of documentation
packages which the specified package depends upon.

=cut

use strict;
use Getopt::Long;
use Carp;

my $gpath = $ENV{GPT_LOCATION};

if (!defined($gpath))
{
  $gpath = $ENV{GLOBUS_LOCATION};

}

if (!defined($gpath))
{
   die "GPT_LOCATION or GLOBUS_LOCATION needs to be set before running this script"
}

@INC = (@INC, "$gpath/lib/perl");

require Grid::GPT::V1::Package;
require Grid::GPT::DepIndexes;

use Cwd;

my $prefix = $ENV{GLOBUS_LOCATION};
my $srcfile;
my $help;
my $debug = 0;
my @deps;

sub pod2usage
{
  if($_[0])
  {
      print "ERROR: $_[0]\n";
  }

  print "Usage: globus_build_doxygen_dependencies -src=src_metadata_file ".
        "[-debug]\n";
  exit($_[0] == 0);
}

GetOptions('src=s'=> \$srcfile,
	   'debug' => \$debug) or pod2usage(1);
pod2usage(0) if $help;
pod2usage('Must specify src_metadata_file') if !defined($srcfile);

@deps = process_package($srcfile);
print join(' ', map {"$prefix/share/doc/$_/html/$_.tag"} @deps) . "\n";

sub process_package($)
{
    my $pkgfile = shift;
    my $pkgname = shift;
    my $deptype = $pkgname ? 'Binary_Dependencies' : 'Source_Dependencies';
    my $pkg;
    my $new_pkgfile;
    my %doc_dependencies;
    my %dependencies;
    my $dep = $deptype eq 'Source_Dependencies' ?  'doc_runtime' : 'Runtime';

    if(! -e $pkgfile)
    {
        croak("Failed dependency check for $pkgname");
    }
    $pkg = new Grid::GPT::V1::Package;
    $pkg->read_metadata_file($pkgfile);

    # oop?
    if(defined($pkg->{$deptype}))
    {
        my $depidx = $pkg->{$deptype};
        my $query_res = $depidx->query(deptype => $dep);

        foreach (@{$query_res})
        {
            my $name;
            if (($name = $_->{pkgname}) ne '')
            {
                print STDERR "Found dependency $name\n" if $debug;
                $dependencies{$name} = 1;
                $new_pkgfile =
                    "$prefix/etc/globus_packages/$name/pkg_data_noflavor_doc.gpt";
                foreach(process_package($new_pkgfile, $name))
                {
                     $dependencies{$_} = 1;
                }
            }
        }
    }
    keys %dependencies;
}
