#!/usr/bin/perl

use strict;
use Data::Dumper;
use RPC::XML qw(smart_encode);
use RPC::XML::ParserFactory;
use LWP::UserAgent;
use HTTP::Request;
# use IO::Socket::SSL;

use lib '../swig/perl';
use ABAC;
ABAC::libabac_init;

use constant {
    USER_AGENT  => 'libabac/0.1',
};

my ($keystore, $url) = @ARGV;
die "Usage: $0 <keystore> <url>\n" unless defined $keystore && defined $url;

# load the certificates
my $context = ABAC::Context->new;
$context->load_directory($keystore);

# build the XML RPC request
my $request = RPC::XML::request->new(
    'abac.query',
    smart_encode({
        role => '06df985dc065fc69b508f6afa8dd127cd29ccc62.fed_create',
        credentials => [
            map {{
                attribute_cert  => RPC::XML::base64->new($_->attribute_cert),
                issuer_cert     => RPC::XML::base64->new($_->issuer_cert),
            }} @{$context->credentials}
        ],
    }),
);

# encode and send the HTTP POST
my $request_body = $request->as_string;

$ENV{HTTPS_CERT_FILE} = 'certs/Jelena_ID.pem';
$ENV{HTTPS_KEY_FILE} = 'certs/Jelena_private.pem';

my $ua = LWP::UserAgent->new;

my $request = HTTP::Request->new(
    'POST',
    "https://$url/RPC2",
);
$request->header('User-Agent', USER_AGENT);
$request->header('Content-Length', length $request_body);
$request->content($request_body);

my $response = $ua->request($request);
if (!$response->is_success) {
    die $response->status_line;
}

# decode the reply
my $xmlrpc_response = RPC::XML::ParserFactory->new->parse($response->decoded_content);
print Dumper $xmlrpc_response;
