#!/usr/bin/env perl

$version = "";
$check = 0;
@tARGV = ();
for (; @ARGV > 0; ) {
    if ($ARGV[0] eq "-version") {
	$version = $ARGV[1];
        shift; shift; next;
    }
    if ($ARGV[0] eq "-check") {
	$check = 1;
        shift; next;
    }
    if ($ARGV[0] eq "-h")     { &usage (); }
    if ($ARGV[0] eq "-help")  { &usage (); }
    if ($ARGV[0] eq "--help") { &usage (); }
    @tARGV = (@tARGV, $ARGV[0]);
    shift;
}
@ARGV = @tARGV;
if ( @ARGV != 0) { &usage (); }

# load the perl module list
$file = "tagsets/ipp-extperl.dst";
open (FILE, $file) || die "ERROR: can't open perl module list: $file\n";
@list = <FILE>;
close (FILE);

# set the psconfig version:
if ("$version" eq "") {
    $version = $ENV{'PSVERSION'};
}
if ("$version" eq "") {
    $version = "default";
}

print "version: $version\n";

$prefix = `csh -f psconfig.sh --prefix $version`; chomp $prefix;
$perldir = `csh -f psconfig.sh --perldir $version`; chomp $perldir;
$homedir = `pwd`; chomp $homedir;

print "prefix: $prefix\n";
print "perldir: $perldir\n";
print "PERL5LIB: $ENV{'PERL5LIB'}\n";

foreach $line (@list) {
    chop $line;
    if ($line =~ m|^\s*$|) { next; }
    if ($line =~ m|^\s*\#|) { next; }

    ($N, $module, $tarball, $prompts) = split (" ", $line);
    
    system ("ckmodule.pl $module");
    if ($? == 0) { 
	# print "$module: found\n";
	next; 
    }

    print "$module: missing\n";
    if ($check) { next; }

    # try to build the module from ../../extperl/Module.*.tar.gz
    chdir "../../extperl";

    print "extract $module from $tarball\n";
    vsystem ("tar xvzf $tarball");
    
    ($tardir) = $tarball =~ m|(\S*).tar.gz|;
    print "tardir: $tardir\n";

    chdir $tardir;

    # build the MakeMaker makefile, setting the output directories
    if ($prompts) {
	@answers = split (",", $prompts);
	open (PIPE, "|perl Makefile.PL PREFIX=$prefix LIB=$perldir");
	foreach $answer (@answers) {
	    print PIPE "$answer\n";
	}
	close (PIPE);
    } else {
	vsystem ("perl Makefile.PL PREFIX=$prefix LIB=$perldir");
    }
    
    vsystem ("make < /dev/null");
    vsystem ("make install");

    chdir $homedir;
}

sub usage {
    print STDERR "USAGE: ckperlmods [-version] [-check]\n";
    exit 2;
}

sub vsystem {
    print STDERR "@_\n";
    $status = system ("@_");
    $status;
}
