#! /usr/bin/perl

# 
# Copyright 1999-2006 University of Chicago
# 
# 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 strict;
use Cwd;
use File::Basename;
use Getopt::Long;

require 5.8.0;
use vars qw(@tests);

$ENV{GLOBUS_USAGE_OPTOUT} = "1";

my $server_pid;
my $server_prog = "$ENV{GRIDFTP_SERVER_EXE}" || "globus-gridftp-server";
my $server_host = "localhost";
my $server_port = 0;
my $subject;

my $server_args = "-no-chdir -d 0 -auth-level 4 -p $server_port";
if ($< != 0)
{
    $server_args = "-no-fork $server_args";
}
chomp($subject = `env OPENSSL_CONF=testcred.cnf openssl x509 -subject -noout -in \${X509_USER_CERT:-testcred.cert} -nameopt rfc2253,-dn_rev `);
$subject =~ s/^subject= */\//;
$subject =~ s/,/\//g;

$server_pid = open(SERVER, "$server_prog $server_args|");
 
if($server_pid == -1)
{
    print "Unable to start server\n";
    exit 1;
}

select((select(SERVER), $| = 1)[0]);
$server_port = <SERVER>;
$server_port =~ s/Server listening at .*?:(\d+)/\1/;
$server_port =~ s/\s+$//;

if($server_port !~ /\d+/)
{
    print "Unable to start server\n";
    exit 1;
}

print STDERR "# Started server at port $server_port\n";

# sleep a second, some hosts are slow....
sleep 1;

$ENV{FTP_TEST_SUBJECT} = $subject;
$ENV{FTP_TEST_CONTACT} = "gsiftp://$server_host:$server_port";

my $rc = system(@ARGV);
print STDERR "# Test exited with $rc\n";

kill 'INT', $server_pid;

if (kill 0, $server_pid) {
    sleep(1);
    if (kill 0, $server_pid) {
        kill 'KILL', $server_pid;
    }
}
exit ($rc>>8);
