#!/usr/bin/perl -w
#
# sudo /www/opals/script/removeBcPrefix -c /etc/opals/conf/ztest
#

use lib '/www/opals/module';
use Opals::Context("/etc/opals/conf/ebi_ebi");
use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);
use Opals::MarcXml qw(
    mxml_writeSortData
);

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


$| = 1;
# fix -- update barcodes
my ($prefix,$lenBc)=('E',6);

my $sth = $dbh->prepare(<<_SQL_);
select    distinct i.rid
from opl_itemInfo ii inner join opl_item i using(barcode)             
where     i.barcode not regexp '^\_\_\_' && ii.sf852Code='c' && ii.sf852Data regexp 'Elmira'  
_SQL_


    $sth->execute;
    my $dir;
    while (my ($rid) = $sth->fetchrow_array) {
        if($rid){
            updateBcFormat($dbh,$rid,$prefix,$lenBc);
        }
    }
    
    $sth->finish;

############################################################
sub formatBc{
    my ($bc,$prefix,$bcLen)=@_;
    my $padLen=$bcLen - length($prefix);
    if( $bcLen <= length($bc)){
        return $bc;
    }
    elsif($bc =~ m/^$prefix(.*)/){
        $bc= sprintf("%s%0*s",$prefix,$padLen,$1);

    }
    else{
        $bc= sprintf("%s%0*s",$prefix,$padLen,$bc);
    }
    return $bc;
}

############################################################
sub updateBcFormat{
    my($dbh,$rid,$prefix,$bcLen) =@_;
    my $zRoot   =  Opals::Context->config('zRoot');
    my $zPort   =  Opals::Context->config('zPort');
    my $zDatabase = Opals::Context->config('zDatabase');
    my $dir     = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);

    unless (-d $dir) {
            mkdir $dir, 0770;
    }        
     
    if (-f "$dir/$rid.xml") {
            my $xml = '';
            open  RECORD, "<$dir/$rid.xml";
            my $line;
            while (<RECORD>) {
                $line = $_;
                if ($line !~ m/<subfield code="-"/) {
                    $xml .= $line;
                }
            }
            my $newSubFields="";
            my $found=0;
            my $change=0;
            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>/){
                    my $bc =$1;
                    my $newBc= formatBc($bc,$prefix,$bcLen);
                    if($newBc ne $bc){
                        $tmp852 =~ s/<subfield code="p">$bc<\/subfield>/<subfield code="p">$newBc<\/subfield>/gi;
                        updateBc($dbh,$bc,$newBc);
                        print "$rid :$bc -> $newBc  \n";                
                        $change=1;
                    }
                   
               }
               
                $newSubFields .= $tmp852;
            }
            close RECORD;
            if($change){
                $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
                $xml = mxml_writeSortData($xml);
                #print "$xml\n";
                open  RECORD, ">$dir/$rid.xml";
                #open  RECORD, ">/tmp/$rid.xml";
                print RECORD $xml;
                close RECORD;
            }

    }
}
############################################################
sub updateBc{
    my($dbh,$oldBc,$newBc)=@_;
    my $sth_item = $dbh->prepare(<<_SQL_);
update opl_item
set barcode=?
where barcode=?
_SQL_

$sth_item->execute($newBc,$oldBc);

my $sth_itemInfo = $dbh->prepare(<<_SQL_);
update opl_itemInfo
set barcode=?
where barcode=?
_SQL_

$sth_itemInfo->execute($newBc,$oldBc);

my $sth_loan = $dbh->prepare(<<_SQL_);
update opl_loan
set barcode=?
where barcode=? 
_SQL_

$sth_loan->execute($newBc,$oldBc);


$sth_item->finish;
$sth_itemInfo->finish;
$sth_loan->finish;
}


############################################################
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;

