#!/usr/bin/perl

eval 'exec /usr/bin/perl  -S $0 ${1+"$@"}'
    if 0; # not running under some shell

use Getopt::Long;
use Cwd;
use Config;

#
# read in the main GPT environment variables
#

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";
}

#
# alter the include path
#

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

if ( ! ( defined eval "require Grid::GPT::GPTObject" ) )
{
    die("$gpath does not appear to hold a valid GPT installation\n");
}

my ($path, @pathdirs);

$path = $ENV{PATH};
@pathdirs = split(/:/, $path);

require Pod::Usage;
require Grid::GPT::GPTIdentity;
require Grid::GPT::PkgMngmt::BuildEnv;

my ($mode, $perl, $force);

GetOptions( 'dir=s' => \$dir,
            'help|?' =>
              sub { setmode("help"); },
            'version' =>
              sub { setmode("version"); },
            'perl' =>
              sub { setmode("perl"); },
            'tar' =>
              sub { setmode("tar"); },
            'gzip' =>
              sub { setmode("gzip"); },
            'gunzip' =>
              sub { setmode("gunzip"); },
            'force' => \$force,
          ) or Pod::Usage::pod2usage(2);

#
# do our directory picking magic here
#

$dir =~ s|\s+||g;

if ( !defined($dir) || (length($dir) == 0) )
{
    $dir = $gpath;
}

#
# sub tar { return "@TAR@" };
# sub gunzip {return "@GUNZIP@"};
# sub gzip {return "@GZIP@"};
# sub mypackage {return "@PACKAGE@"};
# sub default_rpm_license {return "@LICENSE@"};
#

#
# make sure that the directory we've chosen appears to be a valid GPT installation
#

if ( ! -e "$dir/sbin/gpt-install" )
{
    die("'$dir' does not appear to be a valid GPT installation!\n");
}

#
# these are the files requiring interpreter substitution
#

main($mode);

exit;

#
# subroutines
#

### main( $mode )
#
# based on the mode with which we were called, enact the program as desired
#

sub main
{
    my ($mode) = @_;

    #
    # process our different invocation modes
    #

    if ($mode eq "version")
    {
        Grid::GPT::GPTIdentity::print_gpt_version() if defined $version;
    }
    elsif ($mode eq "perl")
    {
        printf("%s\n", getPerl());
    }
    elsif ($mode eq "tar")
    {
        printf("%s\n", Grid::GPT::PkgMngmt::BuildEnv::tar());
    }
    elsif ($mode eq "gzip")
    {
        printf("%s\n", Grid::GPT::PkgMngmt::BuildEnv::gzip());
    }
    elsif ($mode eq "gunzip")
    {
        printf("%s\n", Grid::GPT::PkgMngmt::BuildEnv::gzip());
    }
    elsif ($mode eq "help")
    {
        #
        # if --help is specified, print the synopsis, options, and/or arguments sections
        #

        Pod::Usage::pod2usage(1);

        #
        # doesn't return
        #
    }
    elsif ($mode eq "man")
    {
        #
        # if --man is specified, exit with value 0 and print the entire pod document
        #

        Pod::Usage::pod2usage('-exitval' => 0, '-verbose' => 2);

        #
        # doesn't return
        #
    }
    else
    {
        #
        # otherwise call main
        #

        die("ERROR: Couldn't find mode to operate in.\n");
    }
}

sub getPerl
{
    $data = readFile("$dir/sbin/gpt-install");
    $perl = $data;
    $perl =~ s:^[^#]*#!(\S+)\n.*:\1:s;

    return $perl;
}

### readFile( $filename )
#
# reads and returns $filename's contents
#

sub readFile
{
    my ($filename) = @_;

    open (IN, "$filename") || die "Can't open '$filename': $!";
    $/ = undef;
    $data = <IN>;
    $/ = "\n";
    close(IN);

    return $data;
}

### setmode( $modearg )
#
# based on the mode passed into us, set our program's $mode accordingly
#

sub setmode
{
    my ($modearg) = @_;

    if ( !defined($mode) )
    {
        $mode = $modearg;
    }
    else
    {
        die("Can't run in more than one mode at a time!\n");
    }
}

### action( $command, $dir )
#
# perform some command and inform the user
#

sub action
{
    my ($command, $dir) = @_;
    my $pwd;
    if (defined $dir) {
        $pwd = cwd();
        inform("[ Changing to $dir ]");
        chdir($dir);
    }

    # Log the step
    inform($command);

    # Perform the step
    my $result = system("$command 2>&1");

    if ($result or $?)
    {
        # results are bad print them out.
        die("ERROR: Command failed\n");
    }

    if (defined $dir)
    {
        inform("[ Changing to $pwd ]");
        chdir($pwd);
    }
}

### inform( $content, $override )
#
# inform the user of an event
#

sub inform
{
    my ($content, $override) = @_;

    if ( $verbose or defined($override) )
    {
        print "$content\n";
    }
}

__END__

=head1 NAME

B<gpt-config> - Get various information about the current installation of GPT

=head1 SYNOPSIS

B<gpt-config> [options]

  Help-Related Options:
    --help      brief help message
    --man       full documentation

=head1 OPTIONS

=over 8

=item B<--perl=<path-to-perl>>

Returns the path to perl that GPT is configured to use.

=head2 AUXILIARY MODES

=item B<--version>

Output the current version of GPT.

=item B<--help>

Print a brief help message and exit.

=item B<--man>

Print the manual page and exit.

=back

=head1 DESCRIPTION

B<gpt-config> is a diagnostic script which can give information about the current installation
of GPT.  Please remember to keep your seatbacks and tray tables in their upright positions
during takeoff and landing.

=head1 AUTHOR

Written by Chase Phillips.

=cut
