#!/usr/bin/perl

my $TMPFILE="out-gnutls.tmp";

print "Checking the GnuTLS configuration\n";

my $dir = 'tests/outputs';

opendir(DIR, $dir) or die $!;

my @gnutlspolicies
    = grep {
        /gnutls/          # has gnutls in name
        && -f "$dir/$_"   # and is a file
    } readdir(DIR);

foreach my $policyfile (@gnutlspolicies) {
	my $policy = $policyfile;
	$policy =~ s/-[^-]+$//;

	print "Checking policy $policy\n";

	my $tmp = do {
		local $/ = undef;
		open my $fh, "<", $dir.'/'.$policyfile
			or die "could not open $file: $!";
		<$fh>;
	};

	$tmp =~ s/SYSTEM=//g;
	chomp $tmp;

	system("gnutls-cli --priority '$tmp' -l >$TMPFILE 2>&1");
	if ($? == 0 && $policy eq 'EMPTY') {
		print "Error in gnutls empty policy ($policy)\n";
		print STDERR "gnutls-cli --priority '$tmp' -l\n";
		system("cat $TMPFILE 1>&2");
		exit 1;
	} elsif ($? != 0 && $policy ne 'EMPTY') {
		print "Error in gnutls policy for $policy\n";
		print STDERR "gnutls-cli --priority '$tmp' -l\n";
		system("cat $TMPFILE 1>&2");
		exit 1;
	}
	unlink($TMPFILE);
}

exit 0;
