#!/usr/bin/perl

use Crypt::SSLeay;
use Data::Dumper;
use File::Slurp;
use LWP::Simple;
use RDF::Query;
use RDF::Trine;

print <<HEAD;
\@prefix earl: <http://www.w3.org/ns/earl#> .
\@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .

<#assertor>
	a earl:Software ;
	dc:title "test-harness.pl" .

HEAD


my $endpoint = shift @ARGV ||'https://ophelia.g5n.co.uk:10443/testcases.cgi';

my $manifest = read_file('manifest.ttl');
my $model    = RDF::Trine::Model->new( RDF::Trine::Store->temporary_store );
my $parser   = RDF::Trine::Parser::Turtle->new;
$parser->parse_into_model(undef, $manifest, $model);

my $tests = RDF::Query->new('
PREFIX test: <http://www.w3.org/2006/03/test-description#>
SELECT *
WHERE
{
	?case
		a test:TestCase ;
		test:purpose ?purpose ;
		test:informationResourceInput ?input ;
		test:informationResourceResults ?expected ;
		test:reviewStatus ?status .
}
ORDER BY ?case
')->execute($model);

while (my $test = $tests->next)
{
	$ENV{'HTTPS_PKCS12_FILE'}     = $test->{'input'}->uri . '.p12';
	$ENV{'HTTPS_PKCS12_PASSWORD'} = 'test';
	my $result   = get($endpoint);
	my $expected = read_file($test->{'expected'}->uri . '.txt');
	
	print "[]\ta earl:TestResult ;\n";
	print "\tearl:mode earl:automatic ;\n";
	print "\tearl:mode <#assertor> ;\n";
	print "\tearl:subject <$endpoint> ;\n";
	print "\tearl:test <" . $test->{'case'}->uri . "> ;\n";
	print "\trdfs:comment \"" . $test->{'purpose'}->literal_value . "\" ;\n";

	if ($expected eq $result)
	{
		print "\tearl:result [ earl:outcome earl:passed ] .\n\n" ;		
	}
	else
	{
		print "\tearl:result [ earl:outcome earl:failed ; rdfs:comment \"Expected '$expected', but got '$result'.\" ] .\n\n" ;
	}
}

exit;

