#!/usr/bin/perl -w

BEGIN {
    sub print_help {
    print <<_STR_;
NAME:
    .
SYNOPSIS:
    PERL5LIB=/www/opals/module OPALS_CONF=/etc/opals/conf/\$SITECODE \\
        $0 [param1] [param2] [...]
DESCRIPTION:
    -param1  description 1...
_STR_
    }

    if (!$ENV{'PERL5LIB'} || !$ENV{'OPALS_CONF'}) {
        print_help();
        exit 1;
    }
}

#use Getopt::Std;
#
#my %options = ();
#getopts("c:",\%options);
#my $configFile = $options{c};

use Opals::Context;
use Opals::MarcXml qw(
    mxml_del_rec_holding
);

use strict;
my $dbh = Opals::Context->dbh();;
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...

removeDuplicateBarcodes($dbh);

# Codes end.

exit 0;
################################################################################


sub removeDuplicateBarcodes {
    my ($dbh) = @_;

    my $sth = $dbh->prepare(<<_SQL_);
select  trim(leading 0 from barcode) bc
from    opl_item
where   available = 1
group by trim(leading 0 from barcode) having count(*)>1
_SQL_

    $sth->execute();
    while (my $i = $sth->fetchrow_hashref) {
        my $duplicates = getDuplicates($dbh, $i->{'bc'});

        #foreach my $rid (keys %{$duplicates}) {
        #    foreach my $bc (keys %{$duplicates->{$rid}}) {
        #        print "$rid: $bc\n";
        #    }
        #}
        mxml_del_rec_holding($dbh, $duplicates, 1, 1);
    }
    $sth->finish();
}
############################################################


sub getDuplicates {
    my ($dbh, $barcode) = @_;

    my $sth = $dbh->prepare(<<_SQL_);
select  *
from    opl_item i inner join opl_marcRecord r using (rid)
where   i.available = 1
     && i.barcode = ?
_SQL_

    $sth->execute($barcode);
    my $holding = $sth->fetchrow_hashref();
    $sth->finish();

    $sth = $dbh->prepare(<<_SQL_);
select  *
from    opl_item i inner join opl_marcRecord r using (rid)
where   i.available = 1
     && i.barcode regexp '^0+$barcode\$'
     && (i.rid = ? || r.title = ?)
_SQL_

    my $dup;
    $sth->execute($holding->{'rid'}, $holding->{'title'});
    while (my $i = $sth->fetchrow_hashref()) {
        $dup->{$i->{'rid'}}->{$i->{'barcode'}} = 1;
    }
    $sth->finish();

    return $dup;
}
############################################################


#sub {
#}
############################################################
