#!/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/tsa_sfot");

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::Search qw(
    srch_recordBrief
);

#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 '^\\_\\_\\_' 
order by rid asc 
_SQL_
    $sth->execute;
    my $dir;
    while (my ($rid,$bc) = $sth->fetchrow_array) {
        print "$rid\n";
        #my $newBc=$bc;
        #$newBc =~ s/ /0/g;
        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 $sf852h="";
    my $sf852i="";
    my $sf852c="";
    if($tmp =~ m/<datafield tag="050" ind1="[\d ]" ind2="[\d\- ]">(.*?)<\/datafield>(.*)/s){
        my $f082=$1;
        if($f082 =~ m/<subfield code="a">(.*)<\/subfield>/g){
            $sf852h=$1;
        }
        if($f082 =~ m/<subfield code="b">(.*)<\/subfield>/g){
            $sf852i=$1;
        }
    }
    my $fixed=0;
    my $newSubFields="";
    if($sf852h ne '' || $sf852i ne ''){
        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="h">[ ]*<\/subfield>/g) ||
               ($tmp852 =~ m/<subfield code="i">[ ]*<\/subfield>/g) ||
               ($tmp852 =~ m/<subfield code="c">[ ]*<\/subfield>/g)  ){
                $tmp852 =~ s/<subfield code="h">[ ]*<\/subfield>/<subfield code="h">$sf852h<\/subfield>/gm ;
                $tmp852 =~ s/<subfield code="i">[ ]*<\/subfield>/<subfield code="i">$sf852i<\/subfield>/gm ;
                if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/gm){
                    $bc=$1;
                }
                if($tmp852 =~ m/<subfield code="k">(.*)<\/subfield>/m){
                        $sf852c =$1;
			$newCallNum .="$1 ";
                	$tmp852 =~ s/<subfield code="i">[ ]*<\/subfield>/<subfield code="i">$sf852i<\/subfield>/gm ;

                }
               $newCallNum .="$sf852h ";
               if($tmp852 =~ m/<subfield code="i">(.*)<\/subfield>/m){
                    $newCallNum .="$1 ";
               }
               if($tmp852 =~ m/<subfield code="m">(.*)<\/subfield>/m){
                    $newCallNum .="$1 ";
               }

               $newCallNum =~ s/\s+/ /g;
               $newCallNum =~ s/\s+$//g;
               $tmp852 =~ s/ind1="[\w]"/ind1=" "/g;
               if($tmp852 =~ m/<subfield code="-">(.*?)<\/subfield>/g){
                    $tmp852 =~ s/<subfield code="-">(.*?)<\/subfield>/<subfield code="-">$newCallNum<\/subfield>/g;
               }
               else{
                    $tmp852 =~ s/<\/datafield>/  <subfield code="-">$newCallNum<\/subfield>\n  <\/datafield>/g;
               }
               $fixed=1;
               update_opl_item($dbh, $bc,$newCallNum);
               update_opl_itemInfo($dbh, $bc,$sf852h);
            }
            $newSubFields .= $tmp852;
        }
        $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
    }
    if($fixed){
        update_record($zdbDir, $rid,$xml);
    }

    #$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  = ? 
where   barcode  = ?
_SQL_

     
    $sth->execute($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);
 
}

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