#! /usr/bin/env perl

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

use Globus::Core::Paths;
use POSIX qw(getcwd);
use Test;
use strict;
use Globus::Testing::Container;

my (@tests) = ();
my $pwd = getcwd();
my $containers = {
    c => new Globus::Testing::Container({
            type => 'c',
            security => 0
    }),
    java => new Globus::Testing::Container({
            type => 'java',
            security => 1,
            descriptor => "$pwd/global_security_descriptor.xml"
    })
};
my $c_contact = $containers->{c}->contact();
my $java_contact = $containers->{java}->contact();
my @test_cases = qw(
    instance-creation-test
    immediate-destruction-test
    set-termination-time-test
    get-resource-property-test
    get-multiple-resource-properties-test
    query-resource-properties-test
    set-resource-properties-test
);

push (@tests, map { "test_case(\"$_\", \"$c_contact\")" } @test_cases);
push (@tests, map { "test_case(\"$_\", \"$java_contact\")" } @test_cases);
push (@tests,
    "bad_contact_test(\"immediate-destruction-test\", \"$c_contact\")");
push (@tests,
    "wrong_service_test(\"immediate-destruction-test\", \"$c_contact\")");
push (@tests,
    "bad_contact_test(\"immediate-destruction-test\", \"$java_contact\")");
push (@tests,
    "wrong_service_test(\"immediate-destruction-test\", \"$java_contact\")");
push (@tests,
    "test_case(\"immediate-destruction-test\", \"$c_contact\")");
push (@tests,
    "test_case(\"immediate-destruction-test\", \"$c_contact\")");

plan tests => scalar(@tests);

foreach (@tests)
{
    eval "&$_";
}

sub test_case
{
    my $exec = "$_[0]";
    my $contact = $_[1];
    my $service_contact = "${contact}wsrf/services/WidgetService";

    print "# testing $exec $service_contact\n";
    my $skip = 
            (($exec eq 'query-resource-properties-test' &&
              $contact eq $c_contact)
            || $contact eq '');

    skip($skip, (system {"./$exec"} ($exec, $service_contact)) >>8, 0);
}

sub bad_contact_test
{
    my $exec = "$_[0]";
    my $contact = $_[1];
    my $service_contact = "${contact}wsrf/services/NonWidgetService";

    ok(system("./$exec $service_contact 2> /dev/null") >> 8, 4);
}

sub wrong_service_test
{
    my $exec = "$_[0]";
    my $contact = $_[1];
    my $service_contact = "${contact}wsrf/services/CounterService";

    ok(system("./$exec $service_contact 2> /dev/null") >> 8, 4);
}

sub get_contact {
    my $filename = shift;
    local (*FH);
    local $SIG{ALRM} = sub { die "alarm\n" };
    alarm 60;

    open(FH, "<$filename");

    while (1) {
        while (<FH>) {
            if ($_ =~ m|(http.*)wsrf/services/WidgetService|) {
                return $1;
            }
        }
        select(undef, undef, undef, 10);
    }
}
