#! /usr/bin/env perl

use strict;
use Getopt::Long;
use Cwd;

@INC = ("./tools", @INC);

require DistGPT;

sub commands;

my ($gtar_location, $gunzip_location, $verbose, $version, $help, 
    $man);

my $tarconf="./tarfiles/gpt_tarfiles.conf";

GetOptions( 
           'with-gtar=s'=> \$gtar_location,
           'with-gunzip=s'=> \$gunzip_location,
           'verbose' => \$verbose,
           'man' => \$man,
           'version' => \$version,
           'tarconf=s' => \$tarconf,
          'help' => \$help)
or pod2usage(1);

pod2usage(0) if $help;

my $topdir = cwd();

if (defined $man) {
  my $perl_location = DistGPT::find_perl(
                                         perl_version =>'5.004', 
                                         topdir => $topdir);
  my $podcommand = $perl_location;
  $podcommand =~ s!perl$!pod2text!;
  my $result = system("$podcommand ./setup_gpt_dist");
  exit 0;
}

pod2usage(0) if $help;

print_version() if $version;


my $dist = new DistGPT(
                       gtar => $gtar_location,
                       gunzip => $gunzip_location,
                       tarconf => $tarconf,
                       topdir => $topdir,
                      );

push @INC, $topdir . "/packaging_tools/perl/GPT";

require PkgMngmt::Inform;

my $log = new Grid::GPT::PkgMngmt::Inform(
                                          verbose => $verbose,
                                          name => "setup_gpt_dist",
                                         );

install_core_source($dist);

$log->announce("Unpacking the following tarfiles:\n");

action("mkdir ./support") if ! -d "./support";

for my $key (@{ $dist->get_keys() }) {
  my $t = $dist->{'tars'}->{$key};
  $log->announce("Unpacking $t");
  untar($t, "./support");
}


$dist->match_srcdirs('need_autotools');

install_zlib($dist);

patch_ArchiveTar($dist);

sub install_zlib {
  my ($dist) = @_;
  my $compzlibdir = $dist->{'srcdirs'}->{'perlzlib'};
  my $zlibtar = $dist->{'tars'}->{'zlib'};
  $log->announce("Unpacking $zlibtar");
  untar($zlibtar,$compzlibdir);

  $log->announce("Modifying Compress::Zlib to support $zlibtar");


  opendir ZLIB, $compzlibdir;

  my $zlibmask = DistGPT::get_mask('zlib');

  my @zlibdir = grep { m!$zlibmask! } readdir ZLIB;

  closedir ZLIB;


  #Add to ZLIB's MANIFEST
  my @manditions = `find $compzlibdir/$zlibdir[0] -type f -print`;
  
  open MAN, ">>$compzlibdir/MANIFEST";


  for my $m (@manditions) {
    $m =~ s!$compzlibdir/!!;
#    print $m;
    print MAN $m;
  }

  close MAN;

  action("cp config.in config.orig", $compzlibdir) 
    if ! -f "$compzlibdir/config.orig";

  open(ORIG, "$compzlibdir/config.orig");
  open(OUT, ">$compzlibdir/config.in");

  for (<ORIG>) {
    if (m!BUILD_ZLIB!) {

      if (m!False!) {
        s!BUILD_ZLIB!\#BUILD_ZLIB!;
      }
      if (m!True!) {
        s!\#BUILD_ZLIB!BUILD_ZLIB!;
      }
    }
    if (m!/usr/local!) {
      s!(INCLUDE|LIB).+$!$1 = zlib-1.1.4!;
    }

    print OUT $_;
  }
  close ORIG;
  close OUT;
}

sub patch_ArchiveTar {
  my ($dist) = @_;

  my $applypatch;
  $applypatch = "$topdir/install/bin/applypatch" 
    if -x "$topdir/install/bin/applypatch";

  $applypatch = "applypatch" 
    if system("applypatch --help 2>/dev/null 1>/dev/null")==0 and 
    ! defined $applypatch;

  if (! defined $applypatch) {
    action("./tools/install_makepatch -prefix=$topdir/install");
    $applypatch = "$topdir/install/bin/applypatch";
  }

  my $dir = $dist->{'srcdirs'}->{'perltar'};

  $log->announce("Patching Archive::Tar to complain about bad files");
  action( "$applypatch -verbose -dir=$dir $topdir/tarfiles/ArchiveTar-patch" );
}

sub untar {
  my ($fullname, $dest) = @_;
  my $name = $fullname;
  $name =~ s!^.+/([^/]+)$!$1!;
  my $pwd = cwd();
  action("cp $fullname .", $dest);
  action("$dist->{'gunzip_location'} $name", $dest);
  $name =~ s!\.gz!!;
  action("$dist->{'gtar_location'} xf $name", $dest);
  action("rm $name", $dest);
}

sub action {
  my ($command, $dir) = @_;

  my $startdir = cwd();

  chdir $dir if defined $dir;
  $log->action($command);
  chdir $startdir;
}
sub print_version {
  open (CFG, 'packaging_tools/configure.in');

  my $version;
  for (<CFG>) {
    if (m!AM_INIT_AUTOMAKE\(\w+,([^,\)]+)!) {
      $version = $1;
      $version =~ s!\s+!!g;
      last;
    }
  }
  close CFG;
  print "Globus Packaging Tools Version $version\n";
  exit 0;
}
sub install_core_source {

  $log->announce("Installing globus_core src package");
  my $pwd = cwd();

  action("cp $dist->{'tars'}->{'core'} $pwd/packaging_tools/etc/globus_core-src.tar.gz", 
         "$pwd");
}

sub abspath {
  my ($file) = @_;
  my $home = $ENV{'HOME'};
  $file =~ s!~!$home!;
  my $startd = $topdir;
  $file =~ s!^\./!$startd/!;
  $file = "$startd/$file" if $file !~ m!^\s*/!;
  return $file;
}


=head1 NAME

B<setup_gpt_dist> - Set up a GPT Distribution. 

=head1 SYNOPSIS

setup_gpt_dist [ --with-gtar=<path> --with-gunzip=<path> -override=<DIR> -verbose --help ]

=head1 DESCRIPTION

B<setup_gpt_dist> is a script for setting up a GPT distribution.


=head1 FLAGS

=over 4

=item I<-with-gtar>:  specify the location of GNU tar.

=item I<-with-gunzip>: specify the location of GNU zip.

=item I<-override=<DIR>>: specifies a directory contains the tarfiles
which override the modules and tools included with GPT by default.

=item I<-verbose>:   Print out actions.

=item I<-version>:   Print out GPT version number

=back

=cut
