# This script accepts directory names on the command line and recursively traverses 
# every subtree looking for all the $filename files on that subtree.  
# Each $filename file found is modified. 
# Once a $filename is found in a directory, no further directories are decended on that branch.
#
# George Cross, Borland EIP QA, January 1999.
#

print("\n".$0.":\n");

die "
usage: ".$0." <directory names> \n\n" if !@ARGV;


$filename = 'run.bat';

foreach (<@ARGV>){ traverseSubTree($_); }

sub traverseSubTree()
{
	opendir(THISDIR,@_[0]);
	#print join("\n",readdir(THISDIR))."\n"; print @_[0].'/'.$filename."\n";
	if ( -s @_[0].'/'.$filename != 0 ){ 
		modifyFile(@_[0].'/'.$filename);
	} else{
		foreach (grep(/^[^.]/,readdir(THISDIR))){
			if ( -d @_[0].'/'.$_ != 0 ){
				traverseSubTree(@_[0].'/'.$_);
			}
		}
	}
	closedir(THISDIR);
}

sub modifyFile()
{
	$echoOff = '@echo off'."\n";
	$setCurrentPackage = 'set CURRENT_PACKAGE=%@substr[%_CWD,%@len[%EIS_ROOT%\external\]]'."\n";
	$ifArgsStatement = 'if %1 == smoketests goto smoketests'."\n";
	$gotoEnd = 'goto end'."\n\n";
	$smokeTestsLabel = ':smoketests'."\n";
	$ioRedirection = ' 2>&1>>&stdout_stderr.log'."\n";
	$ifErrorLevelStatements = '@if errorlevel 1 goto FAIL '."\n".'echo %CURRENT_PACKAGE'."\t".'SUCCESS >> %EIS_ROOT%\classes\test\smoketests.log'."\n".$gotoEnd.':FAIL'."\n".'echo %CURRENT_PACKAGE'."\t".'FAIL >> %EIS_ROOT%\classes\test\smoketests.log'."\n".$gotoEnd;
	$end = ':end'."\n".'unset CURRENT_PACKAGE'."\n";

	print "Modifying file:  ".@_[0]."\n";

	# Make a backup copy of our file
	$inFile = @_[0];
	$inFile =~ tr/A-Z/a-z/; 
	$baseFileName = substr($inFile,0,rindex($inFile,"bat"));
	rename $inFile, $baseFileName."old";
	open(INFILE,"<".$baseFileName."old");
	open(OUTFILE, ">".$inFile);

	foreach (<INFILE>){
		if (/^(.*jbuilder_root.*(java|jre).*)$/mi){
			print OUTFILE $echoOff;
			print OUTFILE $setCurrentPackage;
			print OUTFILE "\n";
			print OUTFILE $ifArgsStatement;
			print OUTFILE $_;
			print OUTFILE $gotoEnd;
			print OUTFILE $smokeTestsLabel;
			print OUTFILE $1.$ioRedirection;
			print OUTFILE "\n";
			print OUTFILE $ifErrorLevelStatements;
			print OUTFILE $end
		}else {
			print OUTFILE $_;
		}
	}
	close(OUTFILE);
	close(INFILE);
}
