#!/usr/bin/perl -w

use strict;
use warnings;
use HTTP::OAI;
use XML::LibXML;

print "\n*** start\n";

my $burl = "https://api.archives-ouvertes.fr/oai/hal/";

# sets the HTTP::OAI::Identify object used by the Harvester agent.
my $h = new HTTP::OAI::Harvester(baseURL=>$burl);

# Get a single record from the repository identified by identifier, 
# in format metadataPrefix.
#my $id = "oai:HAL:hal-01473105v1";
my $id = "oai:HAL:ird-01473377v1";

my $r = $h->GetRecord(
	identifier=>$id,
	metadataPrefix=>'oai_dc'
	);

if( $r->is_error ) {
	die("Error harvesting: " . $r->message . "\n");
}

open(my $fh, '>', 'record.txt');
while( my $id = $r->next ) {

	print $fh "identifier => ", $id->identifier,
	($id->status ? " (".$id->status.") " : ''), "\n",
	"datestamp => ", $id->datestamp, "\n";
	foreach($id->header->setSpec) {
		print $fh "setSpec => ", $_, "\n";
	}
	print $fh "\nHeader:\n",
	$id->header->dom->toString;
	print $fh "\nMetadata:\n",
	$id->metadata->toString if defined($id->metadata);
	print $fh "\nAbout data:\n",
	join("\n",map { $_->toString } $id->about) if $id->about;

	my $dom = $id->metadata->dom;
	my $xpc = XML::LibXML::XPathContext->new($dom);
	$xpc->registerNs('dc',  'http://purl.org/dc/elements/1.1/');
	print "\nDownload:\n";
	foreach my $src ($xpc->findnodes('.//dc:identifier')) {
		print "- ", $src->to_literal(), "\n";
	}

}
close $fh;

print "\n*** done\n";
