#!/usr/bin/perl -w
=item
command to update all the sites:

for i in `ls /etc/opals/conf/`; do cp -p /www/opals/script/update_restoreTitle /tmp/urt; perl -pi -e "s/_MY_SITE_/$i/" /tmp/urt; sudo /tmp/urt; done

=cut
use lib '/www/opals/module';
#use Opals::Context("/etc/opals/conf/ztest");
use Opals::Context("/etc/opals/conf/cay_jeh");

use strict;
use DBI;
#use Getopt::Std;
use POSIX qw(
    ceil
);
#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);
my $dbh = Opals::Context->dbh();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...
use Opals::MarcXml qw(
    mxml_writeSortData
);

#my $zdbDir = $config->{'zRoot'} .'/'
#           . $config->{'zPort'} .'/'
#           . 'record' .'/'
#           . $config->{'zDatabase'};

my $zdbDir = Opals::Context->config('zRoot') .'/'
           . Opals::Context->config('zPort') .'/'
           . 'record' .'/'
           . Opals::Context->config('zDatabase');

my $indexDir;
my $attTbl;
my $query_insert ;

my $sth = $dbh->prepare(<<_SQL_);

select  rid,barcode
from    opl_item 
where   barcode not regexp '^\\_\\_\\_'  && callNumber regexp '\/'  
order by rid asc 
_SQL_
    $sth->execute;
    my $dir;
    while (my ($rid,$bc) = $sth->fetchrow_array) {
        print "$rid\n";
        my $xml=fixXmlRecord($dbh,$zdbDir,$rid,$bc);
        #update_record($zdbDir,$rid,$xml);
        #updateTables($dbh,$bc,$newBc);
    }
    $sth->finish;



# Codes end.

exit 0;

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


sub fixXmlRecord {
    my ($dbh,$zdbDir, $rid) = @_;

    my $xml = '';
    my $dir = ceil($rid/1000);
    if (! -f "$zdbDir/$dir/$rid.xml") {
        print "ERROR: $zdbDir/$dir/$rid.xml: not found.\n";
        return;
    }

    #print "$rid\n";
    #return;
    
    open MARCXML, "<$zdbDir/$dir/$rid.xml";
    while (<MARCXML>) {

        $xml .= $_;
    }
    close MARCXML;
    my $tmp =$xml;
    my $sf852k="";
    my $sf852h="";
    my $sf852i="";
    my $sf852c="";
    my $sf852m="";
    my $fixed=0;
    my $newSubFields="";
    while($xml =~ s/([\s]*<datafield tag="852" ind1="[\w ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
        my $tmp852= $1;
        my $newCallNum="";
        my $bc="";
        $sf852c = "";
        if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/gm){
            $bc=$1;
        }
        if($tmp852 =~ m/<subfield code="k">(.*)<\/subfield>/m){
            $sf852k =$1;
        }
       if($tmp852 =~ m/<subfield code="h">(.*)<\/subfield>/m){
            $sf852h =$1;
            if($sf852h =~ s/(\/.*)$//g){
                $fixed=1;
                $tmp852 =~ s/<subfield code="h">(.*)<\/subfield>/<subfield code="h">$sf852h<\/subfield>/g;
            }
       }
       if($tmp852 =~ m/<subfield code="i">(.*)<\/subfield>/m){
            $sf852i =$1;
       }
       if($tmp852 =~ m/<subfield code="m">(.*)<\/subfield>/m){
            $sf852m =$1;
       }
       
       $newSubFields .= $tmp852;
       if($fixed){
            $newCallNum = "$sf852k $sf852h $sf852i $sf852m";
            $newCallNum =~ s/\s+/ /g;
            $newCallNum =~ s/\s+$//g;
            update_opl_item($dbh, $bc,$newCallNum);
            update_opl_itemInfo($dbh, $bc,$sf852h);
       }
    }
    if($fixed){
        $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
        $xml=mxml_writeSortData($xml);
        update_record($zdbDir, $rid,$xml);
    }
    #print "$xml\n";
    #$xml =~ s/<subfield code="p">$bc<\/subfield>/<subfield code="p">$newBc<\/subfield>/g;
    return '';#$record;
}
############################################################


sub update_record{
    my ($zdbDir, $rid,$xml) = @_;
    print "$zdbDir -- $rid\n";
    my $dir = ceil($rid/1000);
    open OUT, ">$zdbDir/$dir/$rid.xml";
    print OUT $xml;
    close OUT;
}
############################################################


sub update_opl_item {
   my ($dbh, $bc,$callNumber) = @_;
   my $sth = $dbh->prepare(<<_SQL_);
update  opl_item
set     callNumber  = ? ,callNumSort_dewey=?
where   barcode  = ?
_SQL_

     
    $sth->execute($callNumber,$callNumber,$bc);
 
}
############################################################
sub update_opl_itemInfo {
   my ($dbh, $bc,$sf852h) = @_;
   my $sth = $dbh->prepare(<<_SQL_);
update  opl_itemInfo
set     sf852Data = ? 
where   barcode  = ? && sf852Code='h'
_SQL_

     
    $sth->execute($sf852h,$bc);
 
}

#////////////////////////////////////////////////////////////////////////////
