#!/usr/bin/perl 

use strict;
use warnings;
use utf8;
use Digest::SHA qw(hmac_sha256_base64);
use Digest::MD5 qw(md5_hex);
use LWP::UserAgent;

my $WSKEY          = 'XjUtp22rwwVRjl3FWI2HMEL7JlKNOFGWlK40c0JyeaqIpeOdLVF5OzSvxJCcHJAFuKfwG14irGfPtoTu';
my $SECRET         = 'lJnp1JEYBIPs2ILajXu8SA==';
my $INSTITUTION_ID = 18464;

my %params = (
	grant_type                  => 'client_credentials',
	authenticatingInstitutionId => $INSTITUTION_ID,
	contextInstitutionId        => $INSTITUTION_ID,
	scope                       => 'WMS_Availability',
);
my $query      = join( "&",  map { $_ . '=' . $params{$_} } sort keys %params );
my $hmac_query = join( "\n", map { $_ . '=' . $params{$_} } sort keys %params );

my $now   = time();
my $nonce = md5_hex( $$, $WSKEY, $now );
my $str   = sprintf( "%s\n%s\n%s\n\nPOST\nwww.oclc.org\n443\n/wskey\n", $WSKEY, $now, $nonce );

if ($hmac_query) {
	$str .= $hmac_query . "\n";
}

my $sig = hmac_sha256_base64( $str, $SECRET );

# Padding hinzufuegen
while (length($sig) % 4) {
	$sig .= '=';
}

my $auth_header = sprintf( 
	'http://www.worldcat.org/wskey/v2/hmac/v1 clientId="%s", timestamp="%s", nonce="%s", signature="%s"',
	$WSKEY, $now, $nonce, $sig
);

my $ua  = LWP::UserAgent->new();
my $req = HTTP::Request->new();

$req->method('POST');
$req->uri( 'https://authn.sd00.worldcat.org/oauth2/accessToken?' . $query );
$req->header( Host => 'authn.sd00.worldcat.org' );
$req->header( Accept => 'application/json' );
$req->header( Authorization => $auth_header );
$req->protocol('HTTP/1.1');

print "\n### REQUEST ", "#" x 68, "\n";
print $req->as_string();
print "-" x 80, "\n";

my $resp = $ua->request($req);

print "\n### RESPONSE ", "#" x 67, "\n";
print $resp->as_string();
print "-" x 80, "\n\n";

if ( $resp->is_success && $resp->content =~ /"(tk_[^"]+)"/ ) {
	my $token = $1;
	my $uri   = sprintf(
		'https://worldcat.org/circ/availability/sru/service?x-registryId=%s&query=%s',
		$INSTITUTION_ID, $ARGV[0] // '49293331'
	);

	my $avail_req = HTTP::Request->new();
	$avail_req->method('GET');
	$avail_req->uri($uri);
	$avail_req->header( Authorization => "Bearer $token" );
	
	my $avail_resp = $ua->request($avail_req);

	print "\n### RESPONSE ", "#" x 67, "\n";
	print $avail_resp->as_string();
	print "-" x 80, "\n\n";
}

