#!/usr/bin/perl -w  

# This program is meant to run the nightly diffcol
# It is meant to be an equivalent for the existing task bash script
# But it is intended to be expanded to work for Windows and GS3
# For windows, need to REMEMBER to set the correct shebangs at the top


# TODO:
# Have a caveat mode and a stable mode (as in snapshot/task.pl)
# 
#} elsif ( $ENV{'TASK_NAME'} =~ "gs2-diffcol-(caveat|stable)" ) {
#	$major_version = 2;
#	$prefix="2t";
#	$rk="tk2"; # test kit
#} elsif ( $ENV{'TASK_NAME'} =~ "gs3-diffcol-(caveat|stable)" ) {
#	$major_version = 3;
#	$prefix="3t";
#	$rk="tk3"; # test kit

package diffcoltask;

use Cwd; 
use Switch; # for switch(val) { case: ; ...}
use File::Path; # for rmdir and mkdir type functions
use File::Copy; # for recursive copying of folders but skipping .svn
use File::Basename;

use strict;
no strict 'subs'; # allow barewords (eg STDERR) as function arguments


my $isWin = ($^O =~ m/mswin/i) ? 1 : 0;
my $isMac = ($^O =~ m/macos|darwin/i) ? 1 : 0;

my $osversion="";
# Need to get the correct gnome-lib-minimal for the OS
# darwin11* Lion, darwin12* Mountain Lion, darwin9* and darwin10* are Leopard and Snow Leopard
if ($^O eq "darwin") {
	$osversion=`uname -r`; # e.g. 12.x.x
	#$osversion =~ s@\..*$@@; # e.g.12
	$osversion = ($osversion =~ m@^1[1-9](\.)?@i) ? "Lion-" : "";
}


my $sep = $isWin ? "\\" : "/";
my $pathsep = $isWin ? ";" : ":";
#my $script_ext = $isWin ? ".bat" : ".bash";
my $setup_script = "setup"; # will become gs3-setup for GS3
my $use_blat = 0; # if we ever get blat to send mail/attachments on Windows working, set this to 1

my $install_type = "svn";
my $install_version = "2";

my $use_local_rebuild = 0; # set to 1 (true) if just diffing and so we needn't copy model-collection over to the test collection again nor rebuild it (This is useful when having built the collection locally once before)
my $use_static_model = 0; # set to 1 (true) if working with a non-svn model-collection. Defaults to 1 if $use_local_rebuild is turned on

# if use_local_rebuild is on, use_static_model should be on
if ($use_local_rebuild && !$use_static_model) {
	$use_static_model = 1;
}

my $test_os = $isWin ? "windows" : ($isMac ? "darwin" : "linux");
my $model_os = "linux"; # default

# TASK_HOME should be the toplevel diffcol folder
$ENV{'TASK_HOME'} = getcwd unless defined $ENV{'TASK_HOME'};
if($isWin) {
	$ENV{'TASK_HOME'} =~ s@\/@\\@g;
	# need to convert TASK_HOME path name to resolve very subtle bug when running task.pl via
	# run-gs2-diffcol.bat which uses environment.pl's TASK_HOME setting via envi
	# At that point TASK_HOME is already defined but ends up lowercase, so that entries in archiveinf-doc 
	# end up sorted differently when db2txt -sort is applied compared to if TASK_HOME had kept its case.	
	require Win32; # for working out Windows Long Filenames from Win 8.3 short filenames
	$ENV{'TASK_HOME'} = &Win32::GetLongPathName($ENV{'TASK_HOME'});
}
##    print STDERR "@@@ TASK_HOME: ".$ENV{'TASK_HOME'}."\n";


$ENV{'BIN_DIR'} = &filename_concat($ENV{'TASK_HOME'}, "bin");

# we'll be using BLAT to send mail attachments on Windows
my $blat = $use_blat ? &filename_concat($ENV{'BIN_DIR'}, "blat", "full", "blat.exe") : 0;
if($isWin && $use_blat && ! -e $blat) {	
	print STDERR "\n***********************************\n";
	print STDERR "No blat.exe found in $blat.\n";
	print STDERR "Blat needed to send mail with attachments on Windows.\n";
	print STDERR "Extract the blat zip file found in $ENV{'BIN_DIR'}\n";
	print STDERR "for your bit architecture and name the folder 'blat'\n";
	print STDERR "***********************************\n\n";
	$blat = 0;
}


$ENV{'DATA_DIR'} = &filename_concat($ENV{'TASK_HOME'}, "diffcol-data");
$ENV{'UPLOAD_DIR'} = &filename_concat($ENV{'TASK_HOME'}, "diffcol-reports");
$ENV{'MONITOR_EMAIL'} = "greenstone_team\@cs.waikato.ac.nz"; # need to escape @ sign
$ENV{'GSDL_SMTP'} = ""; #"smtp.gmail.com";
##print STDERR "@@@ email: ".$ENV{'MONITOR_EMAIL'}."\n";

# control if an existing compiled greenstone is used
# or, if one should be checked out, which revision to checkout from svn
$ENV{'SVN_OPT_REV'} = "-r head";
#$ENV{'GSDLHOME'}=
#$ENV{'GSDL3SRCHOME'}=


# if the first arg is a digit, it's the new envi verbosity param. Take it off the array
my $envi_verbose = shift(@ARGV) if(exists $ARGV[0] && $ARGV[0] =~ m/^\d+$/);

#parse arguments
my $action = "all";
my $subaction = ""; # run_test can take subactions: --just_diff and --no_svn
my @collections = (); # list of collections that run_test should process

if(scalar(@ARGV) == 0) {
    $action="all";
}

# process any arguments that are --gs2|--gs3 and --bin|--svn, and delete them from the array
# if none provided, it's gs2 and svn by default.
for (my $i = $#ARGV; $i >= 0; --$i) { 
    if($ARGV[$i] =~ m/--(bin|svn)/) {
	$install_type = $1;
	splice @ARGV, $i, 1; # remove the element from the argument array
    } elsif($ARGV[$i] =~ m/--gs(2|3)/) {
	$install_version = $1;
	$setup_script = $install_version eq "3" ? "gs3-setup" : "setup"; # needs to become gs3-setup for GS3
	splice @ARGV, $i, 1; # remove the element from the argument array
    }
}


# run_test can take any number of args
if(scalar(@ARGV) > 1 && $ARGV[0] ne "run_test") {
    print STDERR "**** Wrong number of arguments\n";
	&printusage();
	exit -1;
}

if(scalar(@ARGV) > 0) {    
    switch ($ARGV[0]) {
	case qr/^(-h|--?help|help)$/i { &printusage; exit 0; }
	case qr/^(setup_greenstone|run_test|summarise|upload|all)$/ { $action=$ARGV[0]; }
	else { 
	    print STDERR "**** Bad subcommand.\n"; 
	    &printusage; 
	    exit -1;
	}
    }

	# run_test action can take a subaction: nosvn|justdiff. It can also take --modelOS (windows|linux|darwin)
	# nosvn: uses the model-collect as static and copies it over to collect, rebuilding what's currently in model-collect instead of copying 
	# it out from the svn model-collect again.
	# justdiff: same as nosvn, but doesn't copy over model-collection to collect, and doesn't rebuild either of them. Just does the diff part.

	if($action eq "run_test" && scalar(@ARGV) >= 2) {
		push(@collections, @ARGV);
		shift @collections; # remove action from array
		
		for (my $i=0; $i < scalar(@ARGV); $i++) { 
		    if($ARGV[$i] =~ m@^--@) {
			shift @collections; # remove subaction/flag from array
			
			$subaction = $ARGV[$i];
			if($subaction eq "--justdiff") {
			    $use_local_rebuild = $use_static_model = 1;
			} elsif ($subaction eq "--nosvn") {
			    $use_static_model = 1;
			#} elsif ($subaction =~ m/\-\-testOS/i && defined $ARGV[$i+1]) {
			#    $test_os = $ARGV[$i+1];
			#    $i++;
			#    shift @collections; # remove test_os value from array
			} elsif ($subaction =~ m/\-\-modelOS/i && defined $ARGV[$i+1] && $ARGV[$i+1] =~ m/windows|linux|darwin/i) {
			    $model_os = $ARGV[$i+1];
			    $i++;
			    shift @collections; # remove model_os value from array
			    #print STDERR "Model_os specified: $model_os\n";
			} else {
			    print STDERR "**** Bad subaction/value: ".$ARGV[$i]."\n"; 
			    &printusage; 
			    exit -1;
			}
		    }
		}
		
#		foreach my $col (@collections) {
#			print STDERR "Collection: $col\n";
#		}
	}
}

print STDERR "Install type $install_type\n";
print STDERR "Install version $install_version\n";

#check key environment vars are set
if(!defined $ENV{'UPLOAD_DIR'}) {
    print STDERR "Please set a UPLOAD_DIR for the test in an environment.sh file\n";
    #return 1;
}
if(!defined $ENV{'DATA_DIR'}) {
    print STDERR "Please set a DATA_DIR for the test in an environment.sh file\n";
    #return 1;
}
if(!defined $ENV{'MONITOR_EMAIL'}) {
    print STDERR "Please set a MONITOR_EMAIL for the test in an environment.sh file\n";
    #return 1;
}

if($ENV{'DATA_DIR'} eq "/") {
    print STDERR "DATA_DIR should not be the fs root\n";
    #return 1;
} 

print STDERR "DATA_DIR: ".$ENV{'DATA_DIR'}."\n";
print STDERR "UPLOAD_DIR: ".$ENV{'UPLOAD_DIR'}."\n";

#create an id for this test
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
$year += 1900;
$mon += 1;
$mon = "0$mon" if ($mon < 10);
$mday = "0$mday" if ($mday < 10);
my $dateid="$year.$mon.$mday"; #my $dateid=($year+1900)."-".($mon+1)."-$mday";

print STDERR "Starting test '$dateid'\n";


# http://stackoverflow.com/questions/2149368/how-can-i-loop-through-files-in-a-directory-in-perl
$ENV{'CLASSPATH'} = "";
my $jar_lib_path = $ENV{'TASK_HOME'}.$sep."lib";
my @files = <$jar_lib_path/*.jar>; # /full/path/to/diffcol/lib/*jar
foreach my $file (@files) {
	$file =~ s@\/@\\@g if $isWin;
    $ENV{'CLASSPATH'}=$file.$pathsep.$ENV{'CLASSPATH'};
}
##print STDERR "**** classpath: ".$ENV{'CLASSPATH'}."\n";


#set the location of the full report                                               
my $xmlout=filename_concat($ENV{'DATA_DIR'}, "full-report-$install_version-$dateid.xml");
##print STDERR "XML: $xmlout\n";

# the toplevel folder of the greenstone installation being used
my $greenstone3_home="";
my $greenstone_home=""; # gs2build for gs3, toplevel install folder for gs2
# gsdl is the checkout folder and can be greenstone2 or greenstone3
my $gsdl="greenstone2";

# Check if using existing compiled-up greenstone installation
# and set the greenstone_home location accordingly

if(defined $ENV{'GSDL3SRCHOME'} || defined $ENV{'GSDLHOME'}) {
    print STDERR "Found existing Greenstone home, will use that instead\n";
    $greenstone_home=$ENV{'GSDLHOME'} if defined $ENV{'GSDLHOME'};

    if(defined $ENV{'GSDL3SRCHOME'}) {
	print STDERR "*** GSDL3SRCHOME set, changing to using installed GS3\n";
	$gsdl = "greenstone3";
	$install_version = "3";
	$greenstone3_home=$ENV{'GSDL3SRCHOME'};
	$greenstone_home=filename_concat($greenstone3_home, "gs2build") unless defined $ENV{'GSDLHOME'};	
    }
} else {
    if($install_version eq "3") {
	$gsdl = "greenstone3";
	$greenstone3_home=filename_concat($ENV{'DATA_DIR'}, $gsdl);
	$greenstone_home=filename_concat($greenstone3_home, "gs2build");
    } else {
	$greenstone_home=filename_concat($ENV{'DATA_DIR'}, $gsdl);
    }
}
##print STDERR "GSHOME: $greenstone_home\n";

#do the requested action
if($action eq "setup_greenstone") {
    &setup_greenstone;
}
elsif ($action eq "run_test") { 
    &run_test;
}
elsif ($action eq "summarise") {
    &summarise;
}
elsif ($action eq "upload") { 
    &upload;
    &mail_with_report_attached;
}
elsif ($action eq "all") {
    &setup_greenstone;
    &run_test;
    &summarise;
    &upload;
    &mail_with_report_attached;
}

##********************************

sub printusage
{
#    print STDERR "Run as: $0 (help|setup_greenstone|run_test <--modelOS windows|darwin|linux> <--justdiff|--nosvn> <col1 col2 ...> |summarise|upload|all)\n";
    print STDERR "Run as: $0 (help|setup_greenstone|run_test|summarise|upload|all)\n";
    print STDERR "where run_test can further take the following optional parameters:\n";
    print STDERR "\t--modelOS (windows|darwin|linux)\n";
    print STDERR "\t--justdiff|--nosvn\n";
    print STDERR "\t<col1 col2 ...>\n";
    print STDERR "where setup_greenstone can further take the following optional parameters:\n";
    print STDERR "\t--gs2|--gs3\n";
    print STDERR "\t--svn|--bin\n";
}

#http://stackoverflow.com/questions/7427262/read-a-file-and-save-it-in-variable-using-shell-script

sub setup_greenstone
{
    if($install_version eq "3" && !defined $ENV{'JAVA_HOME'}) {
	print "*** JAVA_HOME not set. Set it and add its bin folder to the PATH\n";
	exit 0;
    }

    #clean up from previous tests
    print STDERR "about to clean up any old tests (Ctrl-C to cancel)"; # no newline
    for my $i ( 1..5 ) {
	sleep 1; # 1 second
	print STDERR ".";
    }
    print STDERR "\n";

    # http://perldoc.perl.org/File/Path.html
    print STDERR "cleaning up previous tests\n";
    #&File::Path::remove_tree($ENV{'DATA_DIR'});
    if(-d $greenstone_home && $install_version eq "2") {
	&File::Path::remove_tree($greenstone_home);
    }
    if(-d $greenstone3_home && $install_version eq "3") {
	&File::Path::remove_tree($greenstone3_home);
    }
    unlink glob "$ENV{'DATA_DIR'}$sep"."*report-$install_version*";
    unlink "$ENV{'DATA_DIR'}$sep"."compilation-errors";
    print STDERR "creating the data dir\n";
    #&File::Path::make_path($ENV{'DATA_DIR'}); # works like mkdir -p

    chdir($ENV{'DATA_DIR'});

    # use existing compiled-up greenstone installation, if a GSDLHOME set
    if(defined $ENV{'GSDL3SRCHOME'} || defined $ENV{'GSDLHOME'}) {
	print STDERR "Found existing Greenstone home, will use that instead\n";
	return;
    }

    # Else checkout a GS from svn into DATA_DIR
    if($install_type eq "svn") {
	&checkout_gs_from_svn();
	##print STDERR "$ENV{'DATA_DIR'}$sep$gsdl\n";

	if($install_version eq "2") {
	    &compile_gs2_svn();
	} else {
	    &compile_gs3_svn();
	}
    }

}

sub checkout_gs_from_svn {

    #svn checkout of main gsdl directory                                       
    print STDERR "checkout $gsdl:\n";
    my $cmd = "svn co ".$ENV{'SVN_OPT_REV'}." http://svn.greenstone.org/main/trunk/greenstone$install_version $gsdl";
    ##print STDERR "Checkout CMD: $cmd\n";

    # # unlike backticks operator, system() will print the output of the command to the screen as it executes
    # http://stackoverflow.com/questions/758611/how-to-flush-output-in-backticks-in-perl?rq=1
    my $status = system "$cmd"; #my $status = `$cmd`;
    if($status != 0) {
	print STDERR "@@@ SVN checkout of $gsdl failed\n";
	exit -1;
    }	
    print STDERR "done\n";
}

sub getImageMagickBins {
    my ($cmd, $status);
    my $imagickzip = "";

    chdir ("$greenstone_home");
    if(!$isWin) { # if we're on linux/darwin, need gnome-lib for the correct architecture. And need imagemagick to build imgs in collections
	   
	my $bit_arch=`uname -m`;
	
	# imagemagick binary
	print STDERR "Getting imagemagick binary\n";
	
	my $os = $isMac ? "darwin" : "linux";
	$imagickzip = "imagemagick-$os";
	
	if($isMac) {
#	    $imagickzip .= "-10.5.tar.gz";
	    # at present, only the Imagemagick binaries created by Max for darwin work on the Macs
#	    &File::Path::make_path("$greenstone_home$sep"."bin"."$sep$os"); # need to ensure gsdl/bin/darwin exists
	    $cmd = "svn export http://svn.greenstone.org/main/trunk/binaries/mac/intel/imagemagick bin/darwin/imagemagick";
	    $status = system($cmd);
	    if($status != 0) {
		print STDERR "@@@ Unable to get imagemagick for darwin\n";
	    }
	    
	    # need ghostscript mac binary too for pdf to img conversions on mac
	    $cmd = "svn export http://svn.greenstone.org/main/trunk/binaries/mac/intel/ghostscript bin/darwin/ghostscript";
	    $status = system($cmd);
	    if($status != 0) {
		print STDERR "@@@ Unable to get ghostscript for darwin\n";
	    }
	    
	    # the imagemagick and ghostscript binaries have been set to executable on svn trac now
#	    system("chmod -R u+x $greenstone_home/bin/darwin/imagemagick/bin/*");
#	    system("chmod -R u+x $greenstone_home/bin/darwin/ghostscript/bin/*");
	} else { # linux
	    my $extension64 = ($bit_arch =~ m/64$/) ? "-x64" : "";
	    $imagickzip .= "$extension64.tar.gz";
	
	    # now these next imagemagick steps (and those near the end of this sub) are just for linux, no longer also for mac
	    $cmd = "svn export http://svn.greenstone.org/gs2-extensions/imagemagick/trunk/$imagickzip ext/$imagickzip";
	    $status = system ($cmd);
	    system("cd ext && tar -xvzf $imagickzip");
	}
    }
    return $imagickzip;
}

sub getGnomeLibExt
{
    my ($cmd, $status);
    my $bit_arch=`uname -m`;
    my $os = $isMac ? "darwin" : "linux";

	# gnomelib binary
	print STDERR "setting up gnome-lib-minimal for compilation\n";

	# To get gnome-lib, need to determine bit architecture of the linux/darwin
	# http://stackoverflow.com/questions/8963400/the-correct-way-to-read-a-data-file-into-an-array
	# $Config{'archname64'} doesn't work on the Ubuntu and the Sys::Info package seems to not be supported
	# well on ActivePerl. 
	# But since we know we're on a Linux/Darwin machine at this point, we can just run `uname -m` and other linux cmds

	# osversion will be "Lion" or ""
	# and assuming all darwin is intel, not ppc!!
	my $gnome_lib_file = $isMac ? "darwin-".$osversion."intel" : "linux";

	$gnome_lib_file .= "-x64" if($bit_arch =~ m/64$/ && !$isMac); # linux only case

	#svn checkout gnome-lib for this linux/darwin
	chdir("$greenstone_home$sep"."ext"); #cd $DATA_DIR/$gsdl/ext

	##print STDERR "**** gnomelib: $gnome_lib_file\n";

	# checkout and unpack gnome-lib-minimal

	#svn export http://svn.greenstone.org/gs2-extensions/gnome-lib/trunk/gnome-lib-minimal-linux-x64.tar.gz gl.tar.gz
	$cmd = "svn export http://svn.greenstone.org/gs2-extensions/gnome-lib/trunk/gnome-lib-minimal-".$gnome_lib_file.".tar.gz gl.tar.gz";
	system $cmd;
	system ("tar -xvzf gl.tar.gz");

	##print STDERR "*** ARCH: $bit_arch\n";
}



sub compile_gs3_svn() {
    my ($cmd, $status);
    chdir ("$greenstone3_home");

    $cmd = "ant"; # creates the build.properties file from the .in template
    $status = system $cmd;
    if($status != 0) {
	print STDERR "Unable to run the ant command: $status\n";
	exit -1;
    }
    
    $cmd = "ant -Dproperties.ok=y -Dcheckout.gnomelib.ext=true prepare"; # pass in confirmation to ant prepare step
    $status = system $cmd;
    if($status != 0) {
	print STDERR "Failed to run $cmd command: $status\n";
	exit -1;
    }

    my $imagickzip = &getImageMagickBins();
    chdir ("$greenstone3_home");

    $cmd = "ant -Dcheckout.gnomelib.ext=true install"; # Compile with gnome-lib.
    $status = system $cmd;
    if($status != 0) {
	print STDERR "Failed to run $cmd command: $status\n";
	exit -1;
    }
}

sub compile_gs2_svn() {    
    my $imagickzip = &getImageMagickBins();
    &getGnomeLibExt(); 

    my ($cmd, $status);
    my $os = $isMac ? "darwin" : "linux";

    chdir("$greenstone_home"); #chdir("$ENV{'DATA_DIR'}$sep$gsdl"); # goes into toplevel gs2 or gs3 folder

    ##print STDERR "@@@ OS:  $^O.|".$Config{'archname64'}."|\n";
	
    if($isWin) {
	print STDERR "Compiling $gsdl using makegs2.bat running in auto (silent) mode\n";
	
	# we're now in the GS2 folder, call makegs2 with silent param
	$cmd = "makegs2.bat silent 2>> $ENV{'DATA_DIR'}/compilation-errors"; # STDERR is sent to compilation-errors file
	$status = system $cmd;
	if($status != 0) {
	    print STDERR "Greenstone compilation on Windows failed\n";
	    exit -1;
	}
	
    } else { # if we're on linux/darwin, need gnome-lib for the correct architecture. And need imagemagick to build imgs in collections
	
	chdir("ext$sep"."gnome-lib-minimal");
	
	# need to run source devel.bash on gnome-lib followed by configure, make, make install 
	# in one go, in order to preserve the compile environment set up by sourcing devel.bash

	# http://stackoverflow.com/questions/7369145/activating-a-virtualenv-using-a-shell-script-doesnt-seem-to-work
	# http://ubuntuforums.org/showthread.php?t=1932504 linking /bin/sh to bash instead of dash 
	
#	$cmd = "bash -c \"source ./devel.bash && cd ../.. && ./configure --enable-apache-httpd && make && make install\"";
	$cmd = "bash -c \"";	

	$cmd .= "source ./devel.bash";
	$cmd .= " && cd ../..";

	#configure
	# $cmd .= " && ./configure";
	$cmd .= " && echo 'configure $gsdl: ' ";
        $cmd .= " && echo '<configure>' >> $xmlout";	
        $cmd .= " && ./configure 2>> $ENV{'DATA_DIR'}/compilation-errors"; # configure
        $cmd .= " && echo '</configure>' >> $xmlout";
        $cmd .= " && echo 'done'";

	#make
	$cmd .= " && echo 'make $gsdl: '";
	$cmd .= " && echo '<make>' >> $xmlout";
        $cmd .= " && make 2>> $ENV{'DATA_DIR'}/compilation-errors"; # make
        $cmd .= " && echo '</make>' >> $xmlout";
        $cmd .= " && echo 'done'";

	#make install
	$cmd .= " && echo 'make install $gsdl: '";
        $cmd .= " && echo '<make-install>' >> $xmlout";
	$cmd .= " && make install 2>> $ENV{'DATA_DIR'}/compilation-errors"; # make install
        $cmd .= " && echo '</make-install>' >> $xmlout";
        $cmd .= " && echo 'done'";
	
	$cmd .= "\""; # close off cmd to bash and run it
	$status = system $cmd;

	if(!$isMac) { # Linux
	    # Moving imagemagick after instead of before compilation, since bin/darwin and bin/linux gets overwritten during compilation
	    move("$greenstone_home$sep"."ext/imagemagick/$os", "$greenstone_home$sep"."bin/$os/imagemagick"); # http://www.perlmonks.org/?node_id=586537
	    unlink "$greenstone_home$sep"."ext$sep$imagickzip" or warn "Could not unlink ext/$imagickzip: $!";
	    &File::Path::remove_tree("$greenstone_home$sep"."ext$sep"."imagemagick"); # the untarred parent folder
	}

    }
	
    if($status != 0) {
	print STDERR "@@@ Compilation of Greenstone on Linux/Mac failed\n";
	exit -1;
    }
    
    &getIsisGdl("$greenstone_home"); #&getIsisGdl("$ENV{'DATA_DIR'}/$gsdl");
	
    # set the path to the greenstone_home variable                             
    #$greenstone_home="$ENV{'DATA_DIR'}$sep$gsdl";	
}

sub getPDFBox 
{	
	# current revision is 27763, but using "head" works
	my $PDFBOX_TRAC_URL="http://trac.greenstone.org/export/head/gs2-extensions/pdf-box/trunk/pdf-box-java"; # both for .zip and .tar.gz extension
	#"http://trac.greenstone.org/export/".$ENV{'SVN_OPT_REV'}."/gs2-extensions/pdf-box/trunk/pdf-box-java";	

	# now get the PDFBox extension for PDFBox tutorial	
	print STDERR "Getting pdfbox from $PDFBOX_TRAC_URL:\n";		
	
	chdir($greenstone_home);
	my $cmd = "";
	if ($isWin) {
		$cmd = "setup.bat && cd ext && wget $PDFBOX_TRAC_URL.zip && unzip pdf-box-java.zip";
		
	} elsif ($isMac) { # need to use curl not wget
		$cmd = "cd ext && curl $PDFBOX_TRAC_URL.tar.gz > pdf-box-java.tar.gz && tar -xzf pdf-box-java.tar.gz";
	}
	else { # linux
		$cmd = "bash -c \"export GSDLHOME=&& source setup.bash && cd ext && wget $PDFBOX_TRAC_URL.tar.gz && tar -xzf pdf-box-java.tar.gz\"";
	}
	my $status = system $cmd;
	if($status != 0) {
		print STDERR "@@@ Failed to set up PDFBox\n";
		exit -1; # or proceed to testing other tutorials?
	}
}

sub getOpenOfficeExt
{	
	# current revision is 27763, but using "head" works
	my $OOEXT_TRAC_URL="http://trac.greenstone.org/export/head/gs2-extensions/open-office/trunk/open-office-java"; # both for .zip and .tar.gz extension
	#"http://trac.greenstone.org/export/".$ENV{'SVN_OPT_REV'}."/gs2-extensions/open-office/trunk/open-office-java";	

	# now get the OpenOffice extension for the AllDocTypes collection
	print STDERR "Getting open office ext from $OOEXT_TRAC_URL:\n";		
	
	chdir($greenstone_home);
	my $cmd = "";
	if ($isWin) {
		$cmd = "setup.bat && cd ext && wget $OOEXT_TRAC_URL.zip && unzip open-office-java.zip";
		
	} elsif ($isMac) { # need to use curl not wget
		$cmd = "cd ext && curl $OOEXT_TRAC_URL.tar.gz > open-office-java.tar.gz && tar -xzf open-office-java.tar.gz";
	}
	else { # linux
		$cmd = "bash -c \"export GSDLHOME=&& source setup.bash && cd ext && wget $OOEXT_TRAC_URL.tar.gz && tar -xzf open-office-java.tar.gz\"";
	}
	my $status = system $cmd;
	if($status != 0) {
		print STDERR "@@@ Failed to set up the Open Office Extension\n";
		exit -1; # or proceed to testing other tutorials?
	}
}

sub getIsisGdl {
    my $gsfolder = shift(@_);
    
    if(!$isWin) {
	chdir($greenstone_home);
	my $bit_arch=`uname -m`;
	if ($bit_arch =~ m/64$/) {
	    my $cmd = "";
		 if($isMac) {
			 $cmd = "cd $gsfolder/bin/darwin && curl http://www.greenstone.org/caveat-emptor/IsisGdl.macleopard > IsisGdl && chmod u+x IsisGdl";
		 } else { # linux
			 $cmd = "cd $gsfolder/bin/linux && wget http://www.greenstone.org/caveat-emptor/IsisGdl.bin32 && mv IsisGdl.bin32 IsisGdl && chmod u+x IsisGdl";
		 }
	    my $isis_status = system $cmd;
	    if($isis_status != 0) {
		print STDERR "Unable to get IsisGdl from caveat page\n";
	    }
	}
    }
}

# http://stackoverflow.com/questions/3377879/how-do-i-receive-command-output-immediately
sub run_test
{
    my $collect_parent = $greenstone_home;
    my $model_collect = "model-collect";
    my $build_options = "";
    if($install_version eq "3") {
	$collect_parent = &filename_concat($greenstone3_home,"web","sites","localsite");	
	$model_collect = "gs3-model-collect";
	$build_options = " -site localsite ";
	chdir($greenstone3_home);
    } else {
	chdir($greenstone_home);
    }

	my $num_cols = scalar(@collections); # remember the empty case
	
	if($num_cols == 0) { # deal with all collections
		push (@collections, ""); 
			# putting the empty string in the array so that the "all collections" case 
			# can be handled similar to how the case of user-specified collections is handled
		
	} else { # deal with user specified set of collections
		# prefix the directory separator to each collection name
		@collections = map { $sep.$_ } @collections;
	}

	my $pdfbox = &filename_concat($greenstone_home, "ext", "pdf-box");
	if(!-d $pdfbox) {
		&getPDFBox();
	}

	my $openofficeext = &filename_concat($greenstone_home, "ext", "open-office");
	if(!-d $openofficeext) {
		&getOpenOfficeExt();
	}
	
	#&getIsisGdl("$greenstone_home");

    open (my $xml_fh, '>'.$xmlout) || die "Could not open xml file $xmlout for appending: $!\n";

    # perform the requested subcommands, outputting xml information
    print $xml_fh "<test time=\"$dateid\" id=\"$dateid\">\n";
	
	my ($cmd, $status);
    # make sure that diffcol/model-collect is up to date before copying it over to greenstone-home
	
	if(!$use_local_rebuild) {	
		print $xml_fh "Updating $ENV{'TASK_HOME'}/$model_collect:\n";
		for my $col (@collections) {
			$cmd = "svn up $ENV{'TASK_HOME'}/$model_collect$col"; #chdir("$ENV{'TASK_HOME'}/$model_collect");
			$status = system "$cmd";
		}
	}

    # go to whichever collecthome parent we're using
    chdir($collect_parent);

    # get svn info
    print STDERR "getting svn info: $xmlout\n";
    print $xml_fh "<svn-info>\n";
    &run_and_print_cmd("svn info", $xml_fh);
    print $xml_fh "</svn-info>\n";
    print STDERR "done\n";

	if(!$use_local_rebuild) {
		
		#make two copies of the model-collect directory in gsdl
		#one to be rebuilt and one as the basis for comparison
		#strip both of all .svn directories
	
	    #copy the model collections to the collect folder to be rebuilt
		print STDERR "installing test collections and model collections to new $gsdl installation... ";
		#clean up
		if(-d "collect") {
			for my $col (@collections) {
			    if(-d "collect$col") {
				&File::Path::remove_tree("collect$col") || die "Error could not delete collect: $!";
			    }			
			}	
		}

		if($use_static_model) {	    
			for my $col (@collections) {		
				#copy to collect and strip .svn subfolders
				&File::Path::make_path("collect$col"); # create the collect folder and copy contents from static model-collection across
				&copy_recursively("model-collect$col", "collect$col", ".svn");
			}	

		} else { # the default situation: where we check out the model-collect from svn
			for my $col (@collections) {
				&File::Path::remove_tree("model-collect$col");
				
				#copy to collect and strip .svn subfolders
				&File::Path::make_path("collect$col"); # create the folder and copy contents across
				&copy_recursively(&filename_concat("$ENV{'TASK_HOME'}","$model_collect$col"), "collect$col", ".svn");
				
				#make the model copy
				&File::Path::make_path("model-collect$col"); 
				&copy_recursively("collect$col", "model-collect$col"); # copy contents across
			}
		}

		print STDERR "done\n";
	}	

    #for each collection, import, build and diff with its model counterpart    
	
	# if working with all collections, read the list of collections from the folders in collect
	if($num_cols == 0) {
		@collections = (); # get rid of the empty string put in the array to represent "all collections"
		
		opendir my($collect_handle), "collect" or die "Could not open dir $collect_parent/collect: $!";
	
		for my $collection (readdir $collect_handle) {
			next if ($collection eq "." || $collection eq "..");
			next if ($collection eq "modelcol");
			push(@collections, $collection);			
		}
		closedir $collect_handle; # close handle to collect dir
	}
	
	for my $collection (@collections) {

	#	next if ($collection ne "Demo-Lucene"); ## TEMPORARY, FOR TESTING THIS SCRIPT
	#	next if ($collection !~ m/OAI|METS|DSpace|MGPP|Lucene/); ## TEMPORARY, FOR TESTING THIS SCRIPT

	#escape the filename (in case of space)
	$collection =~ s@ @\\ @g;
	#getting just the basename of the collection would have been necessary had we not cd-ed into $gsdl
	
	$collection =~ s@^[\\/]@@g;	# take the dir-sep prefix away again for user-specified collection names
	
	if (! -d "collect$sep$collection") {
		print STDERR "Collection $collection does not exist\n";
		next;
	}
	
	print STDERR "*** Found collection $collection\n";
	print $xml_fh "<collection-test name=\"$collection\">\n";

	# run the building scripts from the toplevel of the GS installation
	if($install_version eq "3") {
	    chdir($greenstone3_home);
	} else {
	    chdir($greenstone_home);
	}

	if(!$use_local_rebuild) {		
		#import
	# Ensure the OIDtype for importing is hash_on_full_filename
	# "to make document identifiers more stable across upgrades of the software, 
	# although it means that duplicate documents contained in the collection are
	# no longer detected automatically."
		print STDERR "$collection - Importing:\n";
		print $xml_fh "<import>\n";
		&run_build_script("import.pl $build_options -removeold $collection"); #-OIDtype hash_on_full_filename
		print $xml_fh "</import>\n";
		print STDERR "done\n";	

		#build
		print STDERR "$collection - Building:\n";
		print $xml_fh "<build>\n";
		&run_build_script("buildcol.pl $build_options -removeold $collection");
		print $xml_fh "</build>\n";
		print STDERR "done\n";
		
		#rename the intermediate 'building' directory 'index'
		print STDERR "$collection - Move \"building\" to \"index\"... ";
		my $index = &filename_concat($collect_parent, "collect", $collection, "index");
		my $building = &filename_concat($collect_parent, "collect", $collection, "building");
		&File::Path::remove_tree($index);
		# Renaming Directories, http://www.perlmonks.org/?node_id=177421
		move($building, $index) or die "copy failed: $!"; # File::Copy::move
		print STDERR "done\n";
	}
	#diffcol
	print STDERR "$collection - Diffing:\n";
	my $diffcol_dir = &filename_concat($ENV{'TASK_HOME'},"diffcol");
	
#	chdir($collect_parent); # this is actually where we are
	# help diffcol to know on what os the model cols were generated
	# and what os this test machine is (on which the test cols will be generated)
	$cmd = "diffcol.pl -testos $test_os -modelos $model_os -output xml -verbosity 10 $collection"; # need to run with ./diffcol.pl if bash script
	&run_diff_script($cmd, $xml_fh, $diffcol_dir);

	if($install_version eq "3") {
	    chdir($greenstone3_home); # this is actually where we are
	} else {
	    chdir($greenstone_home); # this is actually where we are
	}
	print STDERR "done\n";
	print $xml_fh "</collection-test>\n";
    }

    print $xml_fh "</test>\n";
    close($xml_fh);

    print STDERR "done\n";
}

##***************************************************************
# runs setup in greenstone_home before running the diff command
sub run_diff_script {    
    my ($cmd, $fh, $diffcol_dir) = @_;

    my $linux_ext = ($install_version eq "3") ? "sh" : "bash";

    # we're in greenstone_home now
    if(!$isWin) {	
	$cmd = "bash -c \"export GSDL3SRCHOME=&& export GSDLHOME=&& source $setup_script.$linux_ext && cd $diffcol_dir && ./$cmd\"";

    } else { # Need to prefix cmd -c/-k as necessary
	$cmd = "cmd /c \"set GSDL3SRCHOME=&& set GSDLHOME=&& $setup_script.bat && cd $diffcol_dir && perl -S $cmd\"";
##	print STDERR "@@@@ Going to call command: $cmd\n";	
    }

    return &run_and_print_cmd($cmd, $fh);
}

# runs setup in greenstone_home before running the given build command
sub run_build_script {    
    my ($cmd, $fh) = @_;
    my $linux_ext = ($install_version eq "3") ? "sh" : "bash";

#    chdir($greenstone_home);
    # we are in $greenstone_home already, can directly run the build cmd on the collection
    if(!$isWin) {
	$cmd = "bash -c \"export GSDL3SRCHOME=&& export GSDLHOME=&& source $setup_script.$linux_ext && $cmd\"";

    } else { # Need to prefix cmd -c/-k as necessary
	$cmd = "cmd /c \"set GSDL3SRCHOME=&& set GSDLHOME=&& $setup_script.bat && perl -S $cmd\"";
    }
##     print STDERR "@@@@ Going to call command: $cmd\n";

    return system($cmd);
    #return &run_and_print_cmd($cmd, $fh); # doesn't work on cmds chained with bash -c
}


# http://stackoverflow.com/questions/758611/how-to-flush-output-in-backticks-in-perl?rq=1activeperl%20sys::info
# http://stackoverflow.com/questions/1477500/how-do-i-get-the-output-of-an-external-command-in-perl
sub run_and_print_cmd {
    my ($cmd, $fh) = @_;
    
    open my $pin, "$cmd|" or die "unable to run cmd $cmd: $!"; # open(my $fh, '-|', 'powercfg -l') or die $!;

    if(defined $fh) { # print cmd output both to the filehandle and to stdout
	while (my $line = <$pin>) {
	    print $fh $line;
#	    print STDOUT $line; # if also printing cmd output to STDOUT
	}
    } 
    else { # no filehandle, so just need to print to stdout

	# unlike backticks operator, system() will print the output of the command to the screen as it executes
	# http://stackoverflow.com/questions/758611/how-to-flush-output-in-backticks-in-perl?rq=1
		
	my $status = system $cmd;
	if($status != 0) {
	    print STDERR "ERROR ($status) running $cmd: $!\n";
	}
    }
    close($pin);
}

sub filename_concat {
    my $first_file = shift(@_);
    my (@filenames) = @_;

    # If first_file is not null or empty, then add it back into the list
    if (defined $first_file && $first_file =~ /\S/)
    {
	unshift(@filenames, $first_file);
    }

    my $filename = join($sep, @filenames);
    $filename =~ s/[\\\/]$//; # remove trailing slashes if any
    return $filename;
}


# The following code is from 
# http://stackoverflow.com/questions/227613/how-can-i-copy-a-directory-recursively-and-filter-filenames-in-perl
# It also states that "Perl's File::Copy is a bit broken (it doesn't copy permissions on Unix systems, for example)"
sub copy_recursively {
    my ($from_dir, $to_dir, $regex) = @_;
    opendir my($dh), $from_dir or die "Could not open dir '$from_dir': $!";

#    if(-d !$to_dir) {
#	mkdir $to_dir or die "mkdir '$to_dir' failed: $!" if not -e $to_dir;
#    }

    for my $entry (readdir $dh) {
	next if ($entry eq "." || $entry eq "..");
        next if (defined $regex && $entry =~ /$regex/);
        my $source = "$from_dir/$entry";
        my $destination = "$to_dir/$entry";
        if (-d $source) {
            mkdir $destination or die "mkdir '$destination' failed: $!" if not -e $destination;
            copy_recursively($source, $destination, $regex);
        } else {
            copy($source, $destination) or die "copy failed: $!";
        }
    }
    closedir $dh;
    return;
}

sub summarise {

    # make a summarised Xml report
    print STDERR "Summarizing the xml report... ";
    my $cmd = "java org.apache.xalan.xslt.Process -IN $xmlout -XSL $ENV{'TASK_HOME'}/xsl/xml-report.xsl -OUT $ENV{'DATA_DIR'}/report-$install_version-$dateid.xml";
    my $status = system($cmd);
    print STDERR "done\n";

    # make a summarised HTMl report
    print STDERR "Creating an html summary report... ";
    $cmd = "java org.apache.xalan.xslt.Process -IN $ENV{'DATA_DIR'}/report-$install_version-$dateid.xml -XSL $ENV{'TASK_HOME'}/xsl/html-report.xsl -OUT $ENV{'DATA_DIR'}/report-$install_version-$dateid.html";
    $status = system($cmd);
    print STDERR "done\n";
	
	# Print whether the tests passed or failed                                                      
	print STDERR "*******************************************\n";
    print STDERR "Checking if successful... \n";
    $cmd = "java org.apache.xalan.xslt.Process -IN $xmlout -XSL $ENV{'TASK_HOME'}/xsl/passed-or-not.xsl";    
    $status = `$cmd`; #$status = system($cmd);
    print STDERR "result: $status\n";
	print STDERR "*******************************************\n";
}

sub upload {
    # if the upload dir already existed, clear it of contents
    if (-d $ENV{'UPLOAD_DIR'}) { #else rm $UPLOAD_DIR/*	
	# don't want to keep previous days reports
	# else we will have to manually clear them at some point
	# just generate the set of reports for this run of task.pl upload
	# and 
	&File::Path::remove_tree($ENV{'UPLOAD_DIR'});
    }
    # recreate the upload directory    
    &File::Path::make_path($ENV{'UPLOAD_DIR'});

    # copy all *.xml and *.html files across to UPLOAD_DIR
    opendir my($dh), $ENV{'DATA_DIR'} or die "Could not open DATA_DIR: $!";
    for my $entry (readdir $dh) {
	next if ($entry !~ m/(\.xml|\.html?)$/);
	next if ($entry !~ m/(report-$install_version)/);

	# copy the reports across with different names: with OS prefixed to them. And for the HTML file on Win, rename to HTM
	# html files uploaded from windows to nzdl are empty for no reason. Uploading as htm seems to work
	my $os_entry = $entry; 
	$os_entry =~ s@\.html$@.htm@ if $isWin;
	if($isMac) {
		$osversion = "Leopard-" if ($osversion eq "");
		$os_entry = "diffcol-".$^O."-".$osversion."$os_entry"; # darwin-Lion for Lion/Mountain Lion
	} else {
		$os_entry = "diffcol-".$^O."-$os_entry";
	}
	
	# if the test failed, prefix "failed" to the report so that it shows up with an error icon on the caveat page
	my $cmd = "java org.apache.xalan.xslt.Process -IN $xmlout -XSL $ENV{'TASK_HOME'}/xsl/passed-or-not.xsl";
    my $result = `$cmd`;
    if($result ne "yes") {
		$os_entry =~ s/diffcol-/diffcol-FAIL-/;
	}
	
	# get the absolute path to the original files before copying them over
	$entry = &filename_concat($ENV{'DATA_DIR'}, $entry);		

	# copy them over with their new names
##	print STDERR "@@@@ copying across $entry to $ENV{'UPLOAD_DIR'} as $os_entry\n";
	copy($entry, "$ENV{'UPLOAD_DIR'}$sep$os_entry"); #copy($entry, "$ENV{'UPLOAD_DIR'}");
    }
    closedir $dh;


    # Upload the html file to puka
    #default identity dir
    if ( ! exists $ENV{'IDENTITY_DIR'} ) {
	$ENV{'IDENTITY_DIR'} = "$ENV{'HOME'}${sep}.ssh"; # "C:\\Research\\Nightly\\tools\\keys" on windows, see environment.pl
    }
    if (! exists $ENV{'SNAPSHOT_MODE'} ) {
	$ENV{'SNAPSHOT_MODE'} = "caveat";
    }

    #use the correct key for uploading
    $ENV{'IDENTITY_FILE'} = "$ENV{'IDENTITY_DIR'}${sep}upload-" . $ENV{'SNAPSHOT_MODE'} . ($^O eq "MSWin32" ? ".ppk" : "");
    if(-f $ENV{'IDENTITY_FILE'}) {
	# if you need to touch the file on windows: http://stackoverflow.com/questions/51435/windows-version-of-the-unix-touch-command
	
	# the report we want to upload is actually just os-diffcol-report-$install_version-$dateid.html
	my $command = "cd \"$ENV{'UPLOAD_DIR'}\" && tar -c *.htm* | "; #&& cat *.html | "; # && tar -c * |
	$command .= ($^O eq "MSWin32" ? "plink" : "ssh");
	$command .= " -T -i \"$ENV{'IDENTITY_FILE'}\" nzdl\@puka.cs.waikato.ac.nz";
	#print "$command\n";
	my $status = system("$command");
	if($status != 0) {
	    print STDERR "*** Failed to upload test report to nzdl $status\n";
	}
    } else {
	print STDERR "*** Cannot upload the test report to nzdl from this machine\n";
    }

    print STDERR "Finished uploading\n";
}

# Sending emails with perl: http://learn.perl.org/examples/email.html
# Sending email attachments with perl: http://www.perlmonks.org/?node_id=19430
# Sadly none of the packages are installed by default and use of MIME::Lite is discouraged
sub mail_with_report_attached 
{
    # email out with report attached, if the tests failed                                                      
    print STDERR "Checking if successful... \n";
    my $cmd = "java org.apache.xalan.xslt.Process -IN $xmlout -XSL $ENV{'TASK_HOME'}/xsl/passed-or-not.xsl";
    #my $result = system($cmd);
    my $result = `$cmd`;

    print STDERR "result: $result\n";

    if($result ne "yes") {
	my $msg = "$gsdl regression test for $dateid failed";
	my $subject = "Regression Test Failed"; #"$gsdl regression test for $dateid failed\n";
	my $attach_file = &filename_concat($ENV{'DATA_DIR'}, "report-$install_version-$dateid.html");

	if($isWin) {	
		if($use_blat && $blat && $ENV{'GSDL_SMTP'}) {
			# http://stackoverflow.com/questions/709635/sending-mail-from-batch-file
			#blat -to user@example.com -server smtp.example.com -f batch_script@example.com -subject "subject" -body "body"

			# need to install blat on windows
			$cmd = "$blat -to $ENV{'MONITOR_EMAIL'} -server $ENV{'GSDL_SMTP'} -f $ENV{'MONITOR_EMAIL'} -attach $attach_file -subject \"$subject\" -body \"$msg\"";			
			$result = system($cmd);	
		}
		else {
			$result = 1; # status from running mail command is 0 if success, 1 if fail
			print STDERR "********************************************\n";
			if ($use_blat) {
				print STDERR "Need blat and SMTP set to send mail attachment\n" ;
			} else {	
				print STDERR "Not set up to send mail on Windows\n";
			}
			print STDERR "Inspect report at: $attach_file\n";
			print STDERR "********************************************\n";
		}
	} else { # linux
	    my $status = system("command -v mutt > /dev/null 2>&1;"); #better way of doing "which mutt"
	    
	    if($status != 0) { # mutt doesn't exist, can't send attachments, so send simple email
		$cmd="echo '$gsdl regression test for $dateid failed.' | mail -s 'Regression Test Failed' $ENV{'MONITOR_EMAIL'}";

		print STDERR "********************************************\n";
		print STDERR "No mutt installed, unable to mail attachment\n";
		print STDERR "Inspect report at: $attach_file\n";
		print STDERR "********************************************\n";
	    } else {
		#$cmd = "bash -c \"echo '$gsdl regression test for $dateid failed' | mutt -a $attach_file -s 'Regression Test Failed' -- $ENV{'MONITOR_EMAIL'}\"";
		$cmd = "echo '$gsdl regression test for $dateid failed' | mutt -a $attach_file -s 'Regression Test Failed' -- $ENV{'MONITOR_EMAIL'}";
	    }
		
		# run the mail command
		$result = system($cmd); #&run_and_print_cmd($cmd);
	}

	
	if($result != 0) {
	    print STDERR "*** Unable to send email: $?\n";
	}
	else {
	    print STDERR "Sent mail with report attached.\n";
	}
    } else {
	print STDERR "********************************************\n";
	print STDERR "Tests were successful. Not sending mail.\n";
	print STDERR "********************************************\n";
    }
}

# The old version of this program contained the following, consisting of 1 line of active code:

  # Invoke as: sjmc@br:/research/sjm84/envi/bin$ ./envi diffcol summarise
  # Doing so will call this pl file and pass in "summarise" in ARGV
  # This pl file will in turn call the task executable in this folder 
  # passing in "summarise" as a parameter.
#system("/bin/bash -c \"../etc/tasks/diffcol/task @ARGV\"");

  ##system("/bin/bash -c \"./task @ARGV\"");
  ##print STDERR "/bin/bash -c ../etc/tasks/diffcol/task @ARGV"
  
