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

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="";
    if($tmp =~ m/<datafield tag="082" ind1="[\d ]" ind2="[\d\- ]">(.*?)<\/datafield>(.*)/s){
        my $f082=$1;
        if($f082 =~ m/<subfield code="a">(.*)<\/subfield>/g){
            $sf852h=$1;
 	    $sf852h=~ s/\// /g;
        }
    }
    my $newLangCode="";
    if($sf852h =~ m/^FR[ ]|^R FR[ ]/i){
        $newLangCode='fre';
    }
    if($sf852h =~ m/^SP /i){
        $newLangCode='spa';
    }

    if($newLangCode ne '' && $xml =~ m/<controlfield tag="008">(.*)<\/controlfield>/g){
        my $cf008 =$1;
        my $new008=$1;
        $new008=replaceStr($new008,35,$newLangCode);
        $xml =~ s/<controlfield tag="008">$cf008<\/controlfield>/<controlfield tag="008">$new008<\/controlfield>/g;
    }


    my $fixed=0;
    my $newSubFields="";
    if($sf852h 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="";
		    $tmp852 =~ s/    <subfield code="[\w ]"><\/subfield>\n//gm;
            $tmp852 =~ s/<subfield code="c">(.*)<\/subfield>/<subfield code="d">$1<\/subfield>/g ;
            $tmp852 =~ s/<subfield code="m">(.*)<\/subfield>/<subfield code="j">$1<\/subfield>/g ;
            
            if($tmp852 =~ m/<subfield code="h">(.*)<\/subfield>/g ){
                $tmp852 =~ s/<subfield code="h">(.*)<\/subfield>/<subfield code="h">$sf852h<\/subfield>/gm ;
		        $tmp852 =~ s/    <subfield code="k">(.*?)<\/subfield>\n//g;
		        $tmp852 =~ s/    <subfield code="s">(.*?)<\/subfield>\n//g;
                if($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/gm){
                    $bc=$1;
                }

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

               $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);
	           del_opl_itemInfo_sf($dbh, $bc,'k');
	           del_opl_itemInfo_sf($dbh, $bc,'s');
               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 replaceStr{
    my ($str,$pos,$c)=@_;    
    $str=substr($str,0,$pos) . $c . substr($str,$pos + length($c));
    return $str;    
}

############################################################

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);
 
}
############################################################
sub del_opl_itemInfo_sf{
   my ($dbh, $bc,$sf) = @_;
   my $sth = $dbh->prepare(<<_SQL_);
delete from opl_itemInfo
where   barcode  = ? && sf852Code = ?
_SQL_

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

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