#! /usr/bin/env perl

BEGIN { push(@INC, $ENV{GLOBUS_LOCATION} . "/lib/perl"); }

use strict;
use Test::Harness;
use Cwd;
require 5.005;
use vars qw(@tests);
use Globus::Core::Paths;

my $test_result = 1;
my $kill_gatekeeper = 0;
$|=1;

my $contact;
my $startargs = '-log never ';

@tests = qw(
    globus-gram-job-manager-stdio-test.pl
    globus-gram-job-manager-submit-test.pl
    globus-gram-job-manager-failure-test.pl
    globus-gram-job-manager-proxy-expire-test.pl
    globus-gram-job-manager-rsl-size-test.pl
    globus-gram-job-manager-user-test.pl
);

chdir $Globus::Core::Paths::exec_prefix . "/test/globus_gram_job_manager_test";

if(0 != system("grid-proxy-info -exists -hours 2 2>/dev/null") / 255)
{
    $ENV{X509_CERT_DIR} = cwd();
    $ENV{X509_USER_PROXY} = "testcred.pem";
    system('chmod go-rw testcred.pem'); 
}

if(@ARGV)
{
    $startargs .= join(' ', @ARGV);
}

if(exists($ENV{CONTACT_STRING}))
{
    print "Using gatekeeper at " . $ENV{CONTACT_STRING} . "\n";
    $kill_gatekeeper = 0;
}
else
{
    my $personal_gatekeeper = $Globus::Core::Paths::bindir
                            . "/globus-personal-gatekeeper";
    system("$personal_gatekeeper -killall >/dev/null 2>/dev/null");
    system("$personal_gatekeeper -start $startargs >/dev/null 2>/dev/null");
    chomp($contact = `$personal_gatekeeper -list`);
    if($? != 0)
    {
	print "Could not start gatekeeper\n";
	exit 1;
    }
    $ENV{CONTACT_STRING} = $contact;
    $kill_gatekeeper = 1;
}

$test_result = eval { runtests(@tests) };
if(!defined($test_result))
{
    print $@;
    $test_result=1;
}
else
{
    $test_result=0;
}


sub END {
    if($kill_gatekeeper)
    {
	system("globus-personal-gatekeeper -kill \"$contact\" >/dev/null 2>&1");
    }
    exit $test_result;
}
