#! /usr/bin/env perl
use Cwd;

my $location = getcwd();
my $librarylist = $ARGV[0];
my $ret = 0;

print "Creating personal library for: <$librarylist>\n";

$ENV{PATH} = "PATH=/home/gcc423/bin:/usr/sbin:/usr/sbin:/usr/kerberos/sbin:/usr/sbin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home2/bt/bin";

# Trick here is to install locally after
# extracting the pre-built R and then using
# that R which will have all the paths and
# things right.

my $Rprebuilt = $ARGV[1];
my $Rinstallfrom = $ARGV[2];

print "Using $Rprebuilt\n";
print "Checking where installed\n";
#if($rclue =~ /^(R-\d+\.\d+\.\d+).*$/) {
	#$Rinstallfrom = $1;
#}
#my $Rprebuilt = "built-R-2.10.1.tar.gz";
#my $Rinstallfrom = "R-2.10.1";
my $Rlocation = "$location/R";

if(!(-f $Rprebuilt)) {
	die "No prebuilt R to install locally<$Rprebuilt>.....\n";
} else {
	# prepare an R for this sandbox
	system("tar -zxvf $Rprebuilt");
	chdir("$Rinstallfrom");
	print "doing install from here:\n";
	system("pwd");
	print "About to execute <make prefix=$Rlocation install>\n";
	system("make prefix=$Rlocation install");
	chdir("$location");
}

#$ENV{HOME} = $location;
system("mkdir -p $location/RR");
system("mkdir -p $location/RR/library");

my $localRsources = "Rsources.tar.gz";
if(-f "$localRsources") {
	# extract needed package source
	system("tar -zxvf $localRsources");
}

@libraries = split /,/, $librarylist;

foreach my $lib (@libraries) {
	print "Building <$lib>\n";
	my $cmd = "$Rlocation/bin/R CMD INSTALL --preclean -l $location/RR/library $lib";
	print "Package build:<$cmd>\n";
	$ret = system("$cmd");
	if($ret != 0) {
		print "R library build of $lib failed!!!!\n";
		system("touch RETRYCOMPILE");
		exit(1);
	}
}

system("ls -R RR");
print "Making tar archive......\n";
$ret = system("tar -zcvf RLIBS.tar.gz RR");
if($ret != 0) {
	print "R library build of $lib failed!!!!\n";
	system("touch RETRYCOMPILE");
	exit(1);
}
system("touch COMPILEDONE");
exit(0);
