#!/usr/bin/perl 

###### $GW_LOCATION ############
$gwlocation =  $ENV{'GW_LOCATION'};
################################
$startjobid = $ARGV[0];
$endjobid = $ARGV[1];
print "Agglomeration Script - DSA Group\n";
print "[I] Executing jobs from $startjobid to $endjobid\n";

$jobid = $startjobid;
$lastcommand = "";

@command = ("echo \"Agglomeration start:\" >> output.txt; date >> output.txt");
system (@command) == 0 or die "system @command failed: $?";


while($jobid <= $endjobid)
{
	print "[I] Executing job $jobid\n";
	# Open job.template
	open(JT,"$gwlocation/var/$jobid/job.template");
	@jt = <JT>;
	close(JT);
	foreach $line(@jt)
	{
		chomp($line);
		if ($line =~ "EXECUTABLE")
		{
			($trash,$executable) = split("=",$line);
			
			
		}
		elsif (($line =~ "ARGUMENTS") && ($line !~ "WRAPPER"))
		{
			($trash,$arguments) = split("=",$line);		
		}
	}
	$command = "$executable $arguments";
	if ($command ne $lastcommand)
	{
		@command = ("chmod +x $executable");
		system (@command) == 0 or die "system @command failed: $?";
		@command = ("./$command");
		system (@command) == 0 or die "system @command failed: $?";
		$lastcommand = $command;
	}
	else
	{
		print "That job was executed (Replication)...\n";
	}
	$jobid++;
}

@command = ("echo \"Agglomeration end:\" >> output.txt; date >> output.txt");
system (@command) == 0 or die "system @command failed: $?";
