#! perl

#
# Do a perl check for version >= 5.005.  See 'gpt-translate-interpreter' should you
# need to alter the invocation path to a valid perl interpreter in the GPT front-end
# programs.
#

if ( ! ( defined eval "require 5.005" ) )
{
    die "GPT requires at least Perl version 5.005";
}

#
# dig the globus and gpt paths out of the user's environment variables
#

my $gpt_path = $ENV{GPT_LOCATION};
my $globus_path = $ENV{GLOBUS_LOCATION};
my $gpath;

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

if ( defined($gpt_path) )
{
    $gpath = $gpt_path;
}

if ( defined($globus_path) && !defined($gpath) )
{
    $gpath = $globus_path;
}

if ( ! -d "$globus_path/etc/globus_packages" )
{
    die("Can't find a globus_packages directory to work on in your GLOBUS_LOCATION!\n");
}

#
# standard includes
#

use strict;
use Config;
use Getopt::Long;

@INC = ("$gpath/lib/perl", "$gpath/lib/perl/$Config{'archname'}", @INC);

my( $action, $verbose, $help, $version );

my $actions = [ "both", "file", "filelist", "disk" ];

GetOptions( 'action:s' => \$action,
            'verbose!' => \$verbose,
            'help' => \$help,
            'version' => \$version,
          ) or Pod::Usage::pod2usage(1);

Pod::Usage::pod2usage(0) if $help;
require Grid::GPT::GPTIdentity;
Grid::GPT::GPTIdentity::print_gpt_version() if defined $version;

require Grid::GPT::Installation;

#
# begin main execution
#

if (!defined($action))
{
    $action = "both";
}

if ( !grep(/^$action$/, @$actions) )
{
    die("ERROR: bad action specified");
}

my @files = map
            {
                my $x = $_;
                $x =~ s:/+:/:g;
                $x =~ s:^\s+|\s+$::g;
                $x =~ s:^\./::g;
                $x =~ s:^/::g;
                $x;
            } @ARGV;

if ( ($action eq "both") or ($action eq "filelist") )
{
    my $installation = new Grid::GPT::Installation(
                              pkgdir => "$globus_path/etc/globus_packages",
                              with_filelists => 1,
                              );

    for my $path (@files)
    {
        $installation->removeFilePath( path => $path );
    }

    $installation->saveFilelist();
}

if ( ($action eq "both") or ($action eq "disk") or ($action eq "file") )
{
    for my $path (@files)
    {
        my $fullPath = "$globus_path/$path";
        $fullPath =~ s:/+:/:g;
        system("rm $fullPath");
    }
}

