#!/usr/bin/perl -I /usr/share/eprints3/perl_lib
use warnings;
use strict;
use autodie;
use utf8;

# export single record to get structure:
# sudo -u eprints /usr/share/eprints3/bin/export snz archive XMLFiles 20 > /tmp/20.xml

# Import procedure:

# 3. import with:
# sudo -u eprints /usr/share/eprints3/bin/import --verbose --migration --enable-file-imports --update --enable-import-fields grf eprint XML /tmp/xml
#
# 4. re-run view generation
# sudo -u eprints /usr/share/eprints3/bin/generate_views grf --verbose

use Encode;
use Data::Dump qw(dump);
use Storable;

=for eprints-api

use EPrints;
my $institution = 'Grafički fakultet';

my $ep = EPrints->new();
my $repo = $ep->repository( 'grf' );
$repo->{config}->{enable_file_imports} = 1;
$repo->{config}->{enable_web_imports} = 1;

my $dataset = $repo->dataset( 'eprint' );
my $list = $dataset->search;
my $count = $list->count;
warn "# found [$count] eprints\n";

my $eprint = $dataset->dataobj( 21 );
warn dump( $eprint->get_value('institution'), $institution );

warn dump( $eprint );

if ( $eprint->get_value( 'institution' ) ne $institution ) {
	$eprint->set_value( 'institution' => $institution );
	$eprint->save_revision();
	$eprint->commit();
}

$repo->terminate();

=cut

our $eprintid = 1;

my $files;

my $mkp_path = "/mnt/share/MKP/ELEKTRONIČKI DOKUMENTI/EL.DOKUMENTI PO BIBLIOBROJU/";
my $koha_path = "/tmp/koha_ffzg";

open(my $fh, '-|:encoding(UTF-8)', 'find "' . $mkp_path . '" -iname "*.pdf"');
while(my $full_path = <$fh>) {
	chomp $full_path;

	my $file = $1 if $full_path =~ m{/([^/]+)\.pdf}i;

	my $file_id;
	if ( $file =~ m/(\d+)/ ) {
		$file_id = $1;
	} else {
		$file_id = $file;
	}

	warn "# $file_id\t$full_path\n";
	$files->{ $file_id } = $full_path;

}

warn "# got ", scalar keys %$files, " files\n";

store $files, "$koha_path.biblionumber.file";

my $stat;

open(my $tsv_fh,  '<:encoding(UTF-8)', "$koha_path.tsv");
open(my $marc_fh, '<', "$koha_path.marc");
open(my $import_fh, '>', "$koha_path.import.marc");

my $last_offset = 0;
my @cols;

while(<$tsv_fh>) {
	my $line = $_;
	$line =~ s/[\n\r]+$//;

	if ( ! @cols && $line =~ m/#(.+)/ ) {
		@cols = split(/\t/, $1);
		next;
	}

	my @v = split(/\t/, $_, $#cols + 1);
	my %row;
	@row{@cols} = @v;
warn "## row = ",dump( \%row );

	my $offset = $row{offset} // die "no offset";
	my $biblionumber = $row{biblionumber} || die "no biblionumber";

	warn "# ", join(' ', map { $row{$_} } qw(offset biblionumber title)), "\n";

	exit if $ENV{LAST} && $eprintid >= $ENV{LAST};

	if ( delete $files->{$biblionumber} ) {
		$stat->{file}++;

		seek $marc_fh, $last_offset, 0;
		read $marc_fh, my $marc, $offset - $last_offset;
		print $import_fh $marc;
		warn "# marc $biblionumber\n";

	} else {
		$stat->{missing}++;
	}

	$last_offset = $offset;

}

warn "# files left ", dump($files);

warn "# stat ", dump($stat);
