#!/usr/bin/perl

use warnings;
use strict;

use Data::Dump qw(dump);
use autodie;

use lib '/srv/koha';
use C4::Context;

my $dbh = C4::Context->dbh;

warn "# create t1";
$dbh->do(qq{

create temporary table if not exists t1 as

select
	substr(itemcallnumber,1,2) as prefix,
	substr(itemcallnumber,4) as num,

	items.biblionumber,
	itemnumber, 
	itemcallnumber as signatura, 
	ccode as zbirka, 
	location as lokacija, 
	itype as vrsta_gradje_item,
	itemtype as vrsta_gradje_bib,
	itemlost,
	damaged,
	withdrawn,
	issues,
	renewals,
	onloan
from items
join biblioitems on items.biblionumber=biblioitems.biblionumber
where
	itype <> 'PER' and
itemcallnumber rlike '^[PDFMS][ABCDERO] ';
});

=for comment
/*
./DD-SE/07-MR.sql:where itemcallnumber like 'MR %' and
./DD-SE/08-DR.sql:where itemcallnumber like 'DR %' and
./DD-SE/09-FO.sql:where itemcallnumber like 'FO %' and
./DD-SE/06-DD.sql:where itemcallnumber like 'DD %' and
./DD-SE/10-SE.sql:where itemcallnumber like 'SE %' and

./PC-PE/04-PD.sql:where itemcallnumber like 'PD %' and
./PC-PE/05-PE.sql:where itemcallnumber like 'PE %' and
./PC-PE/03-PC.sql:where itemcallnumber like 'PC %' and

./PA/01-PA.sql:where itemcallnumber like 'PA %' and

./PB/02-PB.sql:where itemcallnumber like 'PB %' and
./PB2/02-PB.sql:where itemcallnumber like 'PB %' and
./PB3/02-PB.sql:where itemcallnumber like 'PB %' and
./PB4/02-PB.sql:where itemcallnumber like 'PB %' and
./PB5/02-PB.sql:where itemcallnumber like 'PB %' and
*/
=cut

my $sth = $dbh->prepare(qq{
select
	prefix,
	num
from t1
order by prefix,num
});

$sth->execute();

my $prefix;
my $num;

while( my $row = $sth->fetchrow_hashref ) {

	$row->{num} =~ s/\s+$//;

	if ( $row->{num} !~ m/^\d+$/ ) {
		warn "SKIP ",dump($row);
		next;
	}

	if ( ! defined $prefix || $prefix ne $row->{prefix}) {
		$prefix = $row->{prefix};
		$num    = $row->{num};
		warn "NEW $prefix $num";
		print "\n";
		next;
	}
	$num++;
	while ( $row->{num} > $num ) {
		print "$prefix $num\n";
		$num++;
	}
}
