#!/usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,
## University of Wisconsin-Madison, WI.
## 
## Licensed under the Apache License, Version 2.0 (the "License"); you
## may not use this file except in compliance with the License.  You may
## obtain a copy of the License at
## 
##    http://www.apache.org/licenses/LICENSE-2.0
## 
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
##**************************************************************


######################################################################
# script to set up for Condor testsuite run
######################################################################

use strict;
use warnings;
use Cwd;
use Env; 
use File::Copy;
use File::Basename;

my $dir = dirname($0);
unshift @INC, $dir;
require "TestGlue.pm";
TestGlue::setup_test_environment();

# Don't buffer output.
$|=1;

my $BaseDir = $ENV{BASE_DIR} || die "BASE_DIR not in environment!\n";
my $logsize = "50000000"; # size for logs of personal Condor
my $force_cygwin = 1; # force a switch to cygwin perl before running batch test.

# Hard-coded filename, defined in test_platform_pre
my $tarball_file = "CONDOR-TARBALL-NAME";

if( -z "tasklist.nmi" ) {
    # our tasklist is empty, so don't do any real work
    print "No tasks in tasklist.nmi, nothing to do\n";
    exit 0;
}


######################################################################
# untar pre-built tarball
######################################################################

my $release_tarball;
my $version;
if( TestGlue::is_windows() ) {
    # if there is a release_dir, assume that the condor binaries are there
    # In that case, no unzipping is needed. just rename release_dir to condor
    if ($ENV{COMPUTERNAME} =~ /^EXEC\-/) {
		if (-d "release_dir" && ! -d "condor") {
		   print "Renaming release_dir/ to condor/\n";
		   rename("release_dir","condor");
		   system("chmod a+x condor/bin/*");
		   TestGlue::dir_listing("condor");
	       
		   my ($release_zipfile) = glob("condor-*.zip");
		   if ($release_zipfile) {
			  $version = substr($release_zipfile, 0, -4);
			  print "VERSION string is $version from $release_zipfile\n";
		   }
		} 
    }
    
    # if there is no release_dir, then look for a zip file
    # containing the condor binaries and unzip it.
    if (!(-d "condor")) {
       print "Finding release zip file\n";
       my ($release_zipfile) = glob("condor-*.zip");
    
       print "Release zip file is '$release_zipfile'\n";
    
       if( ! $release_zipfile ) {
           die "Could not find a condor release zip file!\n";
       }
    
       if ( ! mkdir("condor") ) {
           die "Could not make the condor folder\n";
       }

		# We are explicitly calling unzip from C:\tools so that we do not use Cygwin's
		# version of unzip.  When Cygwin unzips a tarball it removes the execute bits 
		# and we have to restore them.  We want to avoid this so use non-Cygwin unzip
		my $zip_exe_path = "C:\\tools\\unzip.exe";
		if (!(-f $zip_exe_path)) {
		   $zip_exe_path = "msconfig\\unzip.exe";
		}
		print "Unzipping $release_zipfile using $zip_exe_path\n";
		system("$zip_exe_path $release_zipfile -d condor") && die "Can't unzip $release_zipfile: $!\n";
		print "Unzipped $release_zipfile.\n";
	    
		(my $tmp_dir = basename($release_zipfile)) =~ s/\.zip$//;
		print "\$tmp_dir = '$tmp_dir'\n";
		TestGlue::dir_listing("condor");
		my $tmp_dir_path = File::Spec->catdir("condor", $tmp_dir);
		if( -d $tmp_dir_path ) {
			print "$tmp_dir_path exists.  Trying to move...\n";
			system("move $tmp_dir_path\\* condor\\");
		}
		TestGlue::dir_listing("condor");

		$version = substr($release_zipfile, 0, -4);
		print "VERSION string is $version from $release_zipfile\n";
    }
}
else {
    print "Finding release tarball\n";
    open(TARBALL_FILE, '<', $tarball_file ) || die "Can't open $tarball_file: $!\n";
    while(<TARBALL_FILE>) {
        chomp;
        $release_tarball = $_;
    }
    
    print "Release tarball is '$release_tarball'\n";
    
    if( ! $release_tarball ) {
        die "$tarball_file does not contain a filename!\n";
    }
    if( ! -f $release_tarball ) {
        die "$release_tarball (from $tarball_file) does not exist!\n";
    }
    
    print "Release tarball file exists:\n";
    TestGlue::dir_listing($release_tarball);

    print "Untarring $release_tarball ...\n";
    system("tar -xzvf $release_tarball" ) && die "Can't untar $release_tarball: $!\n";
    print "Untarred $release_tarball.\n";
    
    ($version) = $release_tarball =~ /^(.*)\.[^.]+\.[^.]+$/;
    print "VERSION string is $version from $release_tarball\n";
}

######################################################################
# setup the personal condor
######################################################################

print "Condor version: $version\n";

print "SETTING UP PERSONAL CONDOR\n";

# I'm not 100% certain wtf this actually does. 
if( not TestGlue::is_windows() ) {
    mkdir( "$BaseDir/local", 0777 ) || die "Can't mkdir $BaseDir/local: $!\n";
    system("mv $BaseDir/$version $BaseDir/condor" );

	if ( `uname` =~ "Linux" || `uname` =~ "Darwin" ) {
		# On cross-platform testing, the binaries in condor_tests may need
		# to find the extra system libraries we include. Let them find them
		# when looking under $ORIGIN/../lib/condor.
		system( "ln -s condor/lib lib" );
	}
    
    # Remove leftovers from extracting built binaries.
    print "Removing $version tar file and extraction\n";
    unlink(<$version*>);
}
else {
    # windows personal condor setup
    mkdir( "local", 0777 ) || die "Can't mkdir $BaseDir/local: $!\n";
    mkdir( "local/spool", 0777 ) || die "Can't mkdir $BaseDir/local/spool: $!\n";
    mkdir( "local/execute", 0777 ) || die "Can't mkdir $BaseDir/local/execute: $!\n";
    mkdir( "local/log", 0777 ) || die "Can't mkdir $BaseDir/local/log: $!\n";
    
    # Remove leftovers from extracting built binaries.
    print "Removing *.zip files\n";
    unlink(<*.zip>);

    my $Win32BaseDir = $ENV{WIN32_BASE_DIR} || die "WIN32_BASE_DIR not in environment!\n";
   
    if ($^O =~ /MSWin32/) {
        my $which_master = `\@for \%I in (condor_master.exe) do \@echo(%~\$PATH:I`;
        print "which condor_master is $which_master\n";
        if ($which_master =~ /^[a-z]:\\condor\\bin\\/i) {
            print "removing base condor from the path and trying again\n";
            my $tpath = $ENV{PATH};
            $tpath =~ s/^[a-z]:\\condor\\bin[\\]?;//ig;
            $ENV{PATH} = $tpath;
            $which_master = `\@for \%I in (condor_master.exe) do \@echo(%~\$PATH:I`;
            print "which condor_master is now $which_master\n";
        }
    } else {
    	TestGlue::which("condor_master.exe");
    }
    
	# must use cygwin perl on Windows for batch_test.pl in old batlab
	print "Currently running $^O Perl\n";
	if (!($^O =~ /cygwin/)) {
		if ( ! $force_cygwin && ($ENV{COMPUTERNAME} =~ /^EXEC\-/)) {
			print "attempting to run tests using current perl\n";
			#$ENV{PATH} = "$Win32BaseDir\\msconfig;$ENV{PATH}";
			print "PATH=$ENV{PATH}\n";
		} else {
			print "adding cygwin to the front of the path\n";
			$ENV{PATH} = "c:\\cygwin\\bin;$ENV{PATH}";
			print "PATH=$ENV{PATH}\n";

			#$perl_exe = "c:\\cygwin\\bin\\perl";
			#print "Invoking cygwin perl by explicit path ($perl_exe)\n";
			my $perlver = `perl -version`;
			print "----------------------------------\n";
			print $perlver;
			print "----------------------------------\n";
			if (!($perlver =~ /cygwin/i)) {
				die "cygwin perl not found!\n";
			}
		}
	}
}
