#!/usr/bin/perl -w
#
# This script is used to remove all duplicate barcodes.
#
use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);
my %options = ();
getopts("c:",\%options);
my $configFile = $options{c};
if (!$configFile || ! -f $configFile) {
    print "Usage: $0 -c CONFIG_FILE\n";
    exit 1;
}

my $config = loadConfig($configFile);
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# fix -- update barcodes
my $sth = $dbh->prepare(<<_SQL_);
select distinct rid ,rid_o
from tmp_item  
order by rid
_SQL_

    $sth->execute;
    my $dir;
    while (my ($rid,$rid_o) = $sth->fetchrow_array) {
        if($rid){
            print "$rid\n";
            $rid==$rid_o?dedupBc($dbh,$rid):merge($dbh,$rid,$rid_o);
        }
    }
    
    $sth->finish;


############################################################
sub dedupBc{
    my($dbh,$rid) =@_;
    my $zRoot   = $config->{'zRoot'};
    my $zPort   = $config->{'zPort'};
    my $zDatabase = $config->{'zDatabase'};
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);
    my $sth_delItem= $dbh->prepare("delete from opl_item where barcode=?");  
    my $sth_delItemInfo= $dbh->prepare("delete from opl_itemInfo where barcode=?");  
    my $sth_delItemstatus= $dbh->prepare("delete from opl_itemstatus where barcode=?");  
    my $sth_delItemStats= $dbh->prepare("delete from opl_itemStats where barcode=?");  
    my $xml =getMarcXml($rid);
    my $newSubFields="";
    my $curBc="";
    my $dupBc="";
    my $bcList={};
    while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
        my $tmp852 =$1;
        if($tmp852 =~ s/<subfield code="p">(dup_(.*)_(.*))<\/subfield>/<subfield code="p">$2<\/subfield>/i){
            $dupBc=$1;
            $curBc=$2;
        }
        elsif($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/i){
            $curBc=$1;
        }
        if(!defined $bcList->{$curBc}){
            $newSubFields .= $tmp852;
            $bcList->{$curBc}=1;
        }
        if($dupBc ne''){
            print "DUP :: $dupBc \n";
            # delete from opl_item where barcode=$dubBc
            $sth_delItem->execute($dupBc);
            $sth_delItemInfo->execute($dupBc);
            $sth_delItemstatus->execute($dupBc);
            $sth_delItemStats->execute($dupBc);
        }
    }
    $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
    open  RECORD, ">$dir/$rid.xml";
    #open  RECORD, ">/tmp//$rid.xml";
    print RECORD $xml;
    close RECORD;
    #if($newSubFields eq ""){
    #    unlink "$dir/$rid.xml";
    #}
            

    
}

############################################################
sub merge{
 my($dbh,$rid,$rid_o) =@_;
    my $zRoot   = $config->{'zRoot'};
    my $zPort   = $config->{'zPort'};
    my $zDatabase = $config->{'zDatabase'};
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);
    my $sth_delItem         = $dbh->prepare("delete from opl_item where barcode=?");  
    my $sth_delItemInfo     = $dbh->prepare("delete from opl_itemInfo where barcode=?");  
    my $sth_delItemstatus   = $dbh->prepare("delete from opl_itemstatus where barcode=?");  
    my $sth_delItemStats= $dbh->prepare("delete from opl_itemStats where barcode=?");  
    my $sth_itemUpdate=$dbh->prepare("update opl_item set rid=? where barcode=?");
    my $sth_marcDel   =$dbh->prepare("delete from opl_marcRecord where rid=?");
    my $holding_o =getRecHoldingXml($rid_o);
    my $xml =getMarcXml($rid);
    my $newSubFields="";
    my $bcList={};
    my $curBc="";
    my $dupBc="";
    while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
        my $tmp852 =$1;
        if($tmp852 =~ s/<subfield code="p">(dup_(.*)_(.*))<\/subfield>/<subfield code="p">$2<\/subfield>/i){
            $dupBc=$1;
            $curBc=$2;
        }
        elsif($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/i){
            $curBc=$1;
        }
        if(!defined $bcList->{$curBc}){
            $newSubFields .= $tmp852;
            $bcList->{$curBc}=1;
        }
        if($dupBc ne ''){
            # delete from opl_item where barcode=$dubBc
            print "DUP :: merge :: $dupBc \n";
            $sth_delItem->execute($dupBc);
            $sth_delItemInfo->execute($dupBc);
            $sth_delItemstatus->execute($dupBc);
            $sth_delItemStats->execute($dupBc);
        }
        $holding_o->{$curBc}=undef if($holding_o->{$curBc});
    }
    foreach my $h(keys %$holding_o){
        if(defined $holding_o->{$h}){
            print "$rid >>>> $rid_o >> $h\n";
            $newSubFields .= $holding_o->{$h};
            $sth_itemUpdate->execute($rid,$h);
            $sth_marcDel->execute($rid_o);

        }
        else{
            $sth_itemUpdate->execute($rid,$h);
            $sth_marcDel->execute($rid_o);
            print " >> $h\n";
        }
    }
    $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
    open  RECORD, ">$dir/$rid.xml";
    #open  RECORD, ">/tmp//$rid.xml";
    print RECORD $xml;
    close RECORD;
    
       
}

############################################################
sub getRecHoldingXml{
    my ($rid)= @_;
    my $xml=getMarcXml($rid);
    my $holdings={};
    while($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//){
        my $tmp852=$1;
        if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/i){
             $holdings->{$1} = $tmp852;
        }
    }
    return $holdings;
}

############################################################
sub getMarcXml{
    my ($rid)=@_;
    my $zRoot   = $config->{'zRoot'};
    my $zPort   = $config->{'zPort'};
    my $zDatabase = $config->{'zDatabase'};
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    unless (-d $dir) {
            mkdir $dir, 0770;
    }        
     
    my $xml = '';
    if (-f "$dir/$rid.xml") {
        open  RECORD, "<$dir/$rid.xml";
        my $line;
        while (<RECORD>) {
            $xml .= $_;
        }
        close RECORD;
    }
    return $xml;

}


############################################################
sub makeConnection {
    my ($config) = @_;
    if (!$config) {
        return;
    }
    my ($db_driver, $db_name, $db_host, $db_port, $db_user, $db_password);

    $db_driver   = $config->{'db_driver'} || 'mysql';
    $db_name     = $config->{'db_name'};
    $db_host     = $config->{'db_host'};
    $db_port     = $config->{'db_port'}   || '3306';
    $db_user     = $config->{'db_user'};
    $db_password = $config->{'db_password'};

    my $dsn = "dbi:$db_driver:$db_name:$db_host:$db_port";

    return DBI->connect($dsn, $db_user, $db_password);
}


############################################################
sub loadConfig {
    my ($configFile) = @_;
#    print "Enter the config filename of Opals: ";
#    $configFile = <STDIN>;
    my $config = {};

    open CONF, $configFile || die "Cannot open file $configFile";
    while (<CONF>) {
        chomp;
        s/#.*//;                # remove comments
        next if /^\s*$/;        # ignore blank lines

        if (/^\s*(\w+)\s*=\s*(.*?)\s*$/) {
            $config->{$1} = $2;
        }
    }
    close CONF;
    
    return $config;
}
############################################################


exit 0;

