#! /usr/bin/env perl
##**************************************************************
##
## Copyright (C) 1990-2007, 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.
##
##**************************************************************
##
## This test check availability and usage contol of the new
## local, resources in both a static configuration and in psolts.
## It is model after what we did to test concurrency limits
## as we are checking the same sorts of things. bt
##
##**************************************************************

use CondorTest;
use CondorUtils;
use strict;
use warnings;
use Check::SimpleJob;
use Check::CondorLog;

#testreq: personal
my $config = <<CONDOR_TESTREQ_CONFIG;
	XSW_LIMIT = 2
	MACHINE_RESOURCE_Boats = 30
CONDOR_TESTREQ_CONFIG
#endtestreq

my $result = 1;
my $testname = "cmd_submit_coverage";

# we will emit this string into a submit file for use in our testing
#
my $coverage_sub_content = <<COVERAGE_SUB_CONTENT;
accounting_group = fw
arguments =  3600
concurrency_limits = XSW
copy_to_spool = false
coresize = 1000000
cron_day_of_the_month = 5
cron_day_of_the_week = 2
cron_hour = 4
cron_minute = 5
cron_month = 5
cron_prep_time = 60
cron_window = 60
dagman_log = dagman_log
deferral_time = 100
deferral_window = 1000
description = "my test job"
dont_encrypt_input_files = one,two
dont_encrypt_output_files = three,four
encrypt_input_files = five,six
encrypt_output_files = seven,eight
env = MEMORY=$$(memory)|MACHINE=$$(machine)|WONTBE=$$(wontbethere:/be/here/now)
environment = "food=good school=hard"
error = job_core_initialdir_van.err
executable = x_sleep.pl
getenv=true
initialdir = .
job_lease_duration = 3600
job_max_vacate_time = 120
kill_sig = 3
log = job_core_initialdir_van.log
log_xml = false
match_list_length = 5
max_job_retirement_time = (60 * 60 * 48)
max_transfer_input_mb = 1000
max_transfer_output_mb = 1000
nice_user = false
Notification = NEVER
output = job_core_initialdir_van.out
priority = 10
rank = Memory
request_Boats = 1
request_cpus = 1
request_memory = 25
request_disk = 10000
requirements = (Target.name =?= bonanza)
submit_event_notes = "just tracking time"
stack_size = 2048
universe   = vanilla
want_gracefule_removal = true
foo			= Foo1
foo			= Foo2
bar			= Bar
bar			= foo
foo			= bar
foobar		= $(bar)$(foo)
+foo		= "bar"
+bar		= "foo"
+last		= "first"
+done		= FALSE
queue
COVERAGE_SUB_CONTENT

my $ClusterId = 0;

my $submitted = sub {
	print "Submit occured\n";
	runToolNTimes("condor_rm $ClusterId",1,0);
};

my $aborted = sub {
	print "Abort expected\n";
};

my $GetClusterId = sub {
	my $cid = shift;
	$ClusterId = $cid;
	print "Resquestd Cluster Got $ClusterId\n";
	##########################
	#
	# Convoluted: This function is paased to RunCheck which uses it in RunTest in the fourth
	# position which is always an undefined variable EXCEPT when it is a call back routine 
	# to pass out the cluster Id.
	#
	##########################
	#runcmd("condor_q",{emit_output => 1});
};

#Do a job before setting tesing exit codes
TLOG "Testing if SimpleJob runs\n";
$result = SimpleJob::RunCheck(); # jobid 1

TLOG "Creating $testname.sub for coverage test\n";
emit_file("$testname.sub", $coverage_sub_content);

CondorTest::RegisterAbort( $testname, $aborted );
CondorTest::RegisterSubmit( $testname, $submitted );

my $res = CondorTest::RunTest($testname, "$testname.sub", 0, $GetClusterId);
CondorTest::RegisterResult($res, "test_name", $testname);
if($res == 1) {
	CondorTest::debug("$testname: SUCCESS\n",1);
} else {
	CondorTest::debug("$testname: FAILED\n",1);
}

# check command line attribute assignment
TLOG "Testing if submit statements work on submit command line (i.e -append)\n";

my $submit_base = '
	N = 2
	executable = x_sleep.pl
	arguments = $(Process), $(A), $(B), $(D), $(N)
	D = dog
	Queue $(N)
';
my $submit_append = "'A=alpha' 'b=beta' -append 'N=3' -a 'd=delta'";
if (CondorUtils::is_windows()) { $submit_append =~ s/'//g; } # windows doesn't like the ' and doesn't need them

print "\tUsing arguments: $submit_append\n";
print "\tand a submit file that contains:\n$submit_base\n";

my $submit_fname = "cmd_submit_coverage2.$$.submit";
open( SUBMIT, ">$submit_fname" ) || die "error writing to $submit_fname: $!\n";
print SUBMIT $submit_base;
close( SUBMIT );

# remember runCondorTool returns 1 for success.
my $succeeded = 0;
my @ads = ();
$res = runCondorTool( "condor_submit -dry-run - $submit_fname $submit_append", \@ads, 2, {emit_output=>0} );
if ( ! $res) {
	$succeeded = 0;
} else {
	# check the output to see if we got only 2 ads and arguments is "ProcId, alpha, beta, 2"
	my $found = 0;
	my $ids = "";
	my $args = "";
	TLOG "condor_submit -dry relevant output:\n";
	foreach my $line (@ads) {
		if ($line =~ /^ProcId\s*=\s*(\d+)\s*$/i) {
			print "\t$line";
			$ids .= $1;
			++$found;
		} elsif ($line =~ /^Arg[a-z1-9]*\s*=\s*(.*)\s*$/i) {
			print "\t$line";
			if ($1 =~ /"(\d+), alpha, beta, delta, 3"/) {
				$args .= $1;
				++$found;
			}
		}
	}
	TLOG "Expected 6 matching lines with ids='012' args='012'.  found $found matching lines with ids='$ids' args='$args'\n";
	$succeeded = ($found == 6 && $ids eq '012' && $args eq '012');

	# this line gives success with broken -append on queue line for 8.4.0
	#$succeeded = ($found == 4 && $ids eq '01' && $args eq '01');
}
RegisterResult($succeeded,test_name=>$testname, check_name=>"submit_dash_append");

CondorTest::EndTest();

# Helper function to create a file from a string
sub emit_file {
	my $fname = shift;
	my $content = shift;

	open (FH, ">$fname") || die "error writing to $fname: $!\n";
	print FH $content;
	close (FH);
	if ( ! CondorUtils::is_windows()) { chmod (0755, $fname); }
}

