#! /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 Cwd;

use Check::SimpleJob;

my $topleveldir = getcwd();
my $name4test = `whoami`;
CondorUtils::fullchomp($name4test);
CondorTest::debug("Adjusting mapfile for <$name4test>\n",1);
my $mapfileentry = "SSL \"/C=US/ST=Wisconsin/L=Madison/O=HTCondor/CN=Test Credential\" $name4test";

$testdesc =  'lib_auth_protocol-ssl - Security Protocol SSL Authentication Test';
$testname = "lib_auth_protocol-ssl";
$corename = "lib_auth_protocol-ssl";
$mytestnegotiation_result = "yes";

# where am I running
$currenthost = CondorTest::getFqdnHost();

print scalar localtime() . "\n";

$myvariation = 1;

$mypid = $$;
$mysaveme = $corename . ".saveme";

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

# make sure path exists since we have not called StartPersonal yet
my $saveme = $topleveldir . "/" . $mysaveme;
runcmd("mkdir -p $saveme");
my $lowerlevel = $saveme . "/" . $mypid;
runcmd("mkdir -p $lowerlevel");
my $keydir = $saveme . "/" . $mypid . "/ssl_keys";
runcmd("mkdir -p $keydir");

$pidleveldir = $topleveldir . "/" . $mysaveme . "/" . $mypid;

print "changing to $keydir\n";
chdir("$keydir");
my $cmd = ("openssl req -nodes -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -subj \"/C=US/ST=Wisconsin/L=Madison/O=HTCondor/CN=Test Credential\"");
system($cmd);
runcmd("pwd");

$newmap = "condor_mapfile";

open(NEW,">$newmap") || die "Can't open new mapfile:$!\n";
print NEW "$mapfileentry\n";
close(NEW);

chdir("$topleveldir");

my $firstappend_condor_config = '
    DAEMON_LIST = MASTER,SCHEDD,COLLECTOR,NEGOTIATOR,STARTD
    WANT_SUSPEND = FALSE
    ALL_DEBUG = D_ALWAYS
	TOOL_DEBUG = D_ALL
	ALL_DEBUG = D_ALL
	SEC_DEBUG_PRINT_KEYS = TRUE

	SEC_DEFAULT_AUTHENTICATION = REQUIRED
	SEC_CLIENT_AUTHENTICATION = REQUIRED
	SEC_DEFAULT_AUTHENTICATION_METHODS = SSL
';

my $finalappend_condor_config = "
	AUTH_SSL_SERVER_CAFILE =  $keydir/cert.pem
	AUTH_SSL_SERVER_CERTFILE = $keydir/cert.pem
	AUTH_SSL_SERVER_KEYFILE = $keydir/key.pem

	AUTH_SSL_CLIENT_CAFILE =  $keydir/cert.pem
	AUTH_SSL_CLIENT_CERTFILE = $keydir/cert.pem
	AUTH_SSL_CLIENT_KEYFILE = $keydir/key.pem
	SSL_SKIP_HOST_CHECK = true

	CERTIFICATE_MAPFILE = $keydir/condor_mapfile
";

$configfile = CondorTest::CreateLocalConfig($firstappend_condor_config,"libauthprotocolssl",$finalappend_condor_config);

my $testname = "lib_auth_protocol-ssl";

# First order up the config but do not start it. If the condor_config_val fails
# there is no reason to go on

CondorTest::StartCondorWithParams(
    condor_name => "libauthprotocolssl",
    fresh_local => "TRUE",
    condorlocalsrc => "$configfile",
);

$abnormal = sub {
	my %info = @_;

	die "Do not want to see abnormal event\n";
};

$aborted = sub {
	my $done;
	%info = @_;
	$cluster = $info{"cluster"};
	$job = $info{"job"};

	die "Do not want to see aborted event\n";
};

$held = sub {
	my $done;
	%info = @_;
	$cluster = $info{"cluster"};
	$job = $info{"job"};

	die "Do not want to see aborted event\n";
};

$executed = sub
{
	%info = @_;
	$cluster = $info{"cluster"};

	my @adarray;
	my $status = 1;
	my $cmd = "condor_q -debug";
	#$status = CondorTest::runCondorTool($cmd,\@adarray,2,"Security");
	$status = CondorTest::runCondorTool($cmd,\@adarray,2,{emit_output=>0});
	if(!$status) {
		CondorTest::debug("Test failure due to Condor Tool Failure<$cmd>\n",1);
		exit(1);
	} else {
		foreach $line (@adarray) {
			if( $line =~ /.*Authentication was a Success.*/ ) {
				CondorTest::debug("SWEET: client got Authentication as expected\n",1);
				return(0);
			}
		}
		CondorTest::debug("Bad: client did not get Authentication as expected\n",1);
		exit(1)
	}
};

$submitted = sub
{
	my %info = @_;
	my $cluster = $info{"cluster"};

	CondorTest::debug("submitted: \n",1);
	{
		CondorTest::debug("Check authenticated user....\n",1);
	}
	my @adarray;
	my $status = 1;
	my $cmd = "condor_q -l $cluster";
	$status = CondorTest::runCondorTool($cmd,\@adarray,2,{emit_output=>0});
	if(!$status) {
		CondorTest::debug("Test failure due to Condor Tool Failure<$cmd>\n",1);
		exit(1);
	} else {
		foreach $line (@adarray) {
			if( $line =~ /^Owner\s*=\s*(.*)\s*.*/ ) {
				CondorTest::debug("Owner is $1\n",1);
			} elsif ( $line =~ /^User\s*=\s*(.*)\s*.*/ ) {
				CondorTest::debug("User is $1\n",1);
			}
		}
	}
};

$success = sub
{
	my %info = @_;
	my $cluster = $info{"cluster"};

	my $stat = CondorTest::SearchCondorLog( "SCHEDD", "Authentication was a Success" );
	if( $stat == 1 ) {
		CondorTest::debug("Good completion!!!\n",1);
	} else {
		die "Expected match for Authentication is a Success and could not find it in SchedLog\n";
	}

};

CondorTest::RegisterExitedAbnormal( $testname, $abnormal );

my $result = SimpleJob::RunCheck(
	test_name => $testname,
	on_hold => $held,
	on_abort => $aborted,
	on_execute => $executed,
	on_submit => $submitted,
	on_success => $success
	);

CondorTest::EndTest();

exit(0);
