#! /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.
##
##**************************************************************

use CondorTest;
use CondorUtils;
use CondorCmdStatusWorker2;
use strict;
use warnings;

# truly const variables in perl
sub IDLE{1};
sub HELD{5};
sub RUNNING{2};

my $testname = "cmd_status_shows-submitters";
my $debuglevel = 2;

print scalar localtime() . "\n";

my $mypid = $$;

if($mypid == 0) {
	die "Saveme setup for test failed\n";
}

CondorTest::debug("Master PID is $mypid\n",$debuglevel);

my $outsource = CondorCmdStatusWorker2::SetUp("cmd_status_shows-submitters");
CondorUtils::fullchomp($outsource);

if($outsource eq "") {
    # assume all cleanup of personals which did start occurred in worker
    print "OOOOPPPPSSSSSSSSSSSSyyyyy\n";
    exit(1);
}

( my $locconfig, my $scheddoneconfig) = split('&',$outsource);
CondorTest::debug("Two pools are $locconfig and $scheddoneconfig\n",$debuglevel);

my $done = 0;
my $stable = CondorCmdStatusWorker2::IsSystemStable();
my @adarray = (); 
my $cmd = "";
my $cmdstatus;

my $numclaimed = 0;

if($stable == 1) {
    # allow time for all the nodes to update the collector
    # by allowing N attempts
    # with 4 run forever jobs we are not stable until -claimed finds exactly 4
    my $nattempts = 8;
    my $count = 0;

	print "Looking for at least 2 claimed slots - ";
    while($count < $nattempts) {
        $cmd = "condor_status -claimed -format \"%s\\n\" name";
        CondorTest::debug("Looking for exactly 4 claimed slots\n",$debuglevel);
        $cmdstatus = CondorTest::runCondorTool($cmd,\@adarray,2);
        if(!$cmdstatus)
        {
            CondorTest::debug("Test failure due to Condor Tool Failure<$cmd>\n",$debuglevel);
			last;
        }

        # 4 are busy so 4 should be claimed....
		# some could be evicted at the momment so 2 or more ok

        $numclaimed = 0;
        foreach my $line (@adarray) {
            if($line =~ /^\s*slot(\d+)[@]master.*@.*$/) {
                $numclaimed = $numclaimed + 1;;
                CondorTest::debug("found claimed slot: $numclaimed of 4\n",$debuglevel);
            } else {
                #print "skip: $line\n";
            }
        }

        if($numclaimed >= 2) {
            CondorTest::debug("Condor_status -claimed found $numclaimed slots\n",$debuglevel);
            $done = 1;
			print "ok\n";
            last;
        } else {
            CondorTest::debug("Condor_status -claimed found incorrect claimed slot count<$numclaimed>\n",$debuglevel);
        }

        $count = $count + 1;
		sleep($count * 5);
    }
}

if($done == 0) {
	print "bad\n";
}

 
my $numsubmitters = 0;
my %discoveries = ();
my @expectations = ("Submitter", "Negotiator", "DaemonMaster", "Scheduler", "Machine");

if($done == 1) {
# process one of each ad type and then compare with expected list
	my $nattempts = 8;
	my $jobcount = 0;
	my $count = 0;

	print "Looking for at least 2 jobs - ";
	while($count < $nattempts) {
		#$cmd = "condor_status -submitters -format \"<%s:\" Name -format \"%s:\" Machine -format \"%d>\\n\" RunningJobs";
		$cmd = "condor_status -submitters -af Name  Machine RunningJobs";
		#$cmd = "condor_status -submitters -l ";
		CondorTest::debug("Looking at -submitters($cmd)\n",$debuglevel);
		$cmdstatus = CondorTest::runCondorTool($cmd,\@adarray,2);
		$jobcount = 0;
	    if(!$cmdstatus)
	    {
	        CondorTest::debug("Test failure due to Condor Tool Failure<$cmd>\n",$debuglevel);
			$done = 0;
			last;
	    }
		
		# we know we have 2 jobs in each of the two pools
		$jobcount = 0;
		foreach my $line (@adarray) {
			fullchomp($line);
			CondorTest::debug("-submitters: $line\n",$debuglevel);
			if( $line =~ /^(.*?)\s+(.*?)\s+(\d+).*$/ ) {
				$jobcount = $jobcount + $3;
				CondorTest::debug("JobCount up to $jobcount.\n",$debuglevel);
			} else {
				print "Parse failed:$line:\n";
			}
		}

		if($jobcount >= 2) {
			CondorTest::debug("SUCCESS: Found 4 running jobs from -submittors\n",$debuglevel);
			last;
		}

		$count = $count + 1;
		sleep($count * 2);
	}

	if($jobcount < 2) {
		print "bad\n";
		$done = 0;
		CondorTest::debug("Test failed because this submitter expected to have 2 or more running jobs not ($jobcount)\n",$debuglevel);
	}

}


if($done == 1) {
	print "ok\n";
} else {
	print "bad\n";
}


CondorTest::debug("Saving things and cleaning up....\n",$debuglevel);

#fails due to directory that matches symbol

my $res = 1;
my @rm1 = ();
my @rm2 = ();
$ENV{CONDOR_CONFIG} = $locconfig;
$res = runCondorTool("condor_rm -all",\@rm1,2,{emit_output=>0});
$ENV{CONDOR_CONFIG} = $scheddoneconfig;
$res = runCondorTool("condor_rm -all",\@rm2,2,{emit_output=>0});

print scalar localtime() . "\n";

if( $done == 0 )
{
	# actual test failed but we allowed cleanup
	RegisterResult(0,"test_name", "$testname");
	CondorTest::EndTest();
	exit(1);
} else {
	RegisterResult(1,"test_name", "$testname");
	CondorTest::EndTest();
	CondorTest::debug("cmd_status_shows-submitters SUCCESS\n",$debuglevel);
}
exit(0);
