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

use strict;
use DBI;
use Opals::MarcXml qw(
    mxml_update
);

#use Getopt::Std;
use POSIX qw(
    ceil
);
my $dbh = Opals::Context->dbh();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...

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 distinct rid from opl_item where barcode not regexp '^\_\_\_'   order by rid ; 
_SQL_

    $sth->execute;
    my $fixed=0;
    my $count =0;
    open logFile ,">/tmp/restoreBcFromSql2Xml.log";
    while (my ($rid) = $sth->fetchrow_array) {
        #print "$rid\n";
        my $dir =$zdbDir ."/" .ceil($rid/1000);
        my $xml =getRecXml($dir,$rid);
        my $bcList =getBbList($dbh,$rid);
        my $newSubFields="";
        my $tmp852 ="";
        while ($xml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)+[\s]*<\/datafield>)//) {
                $tmp852 =$1;
                $newSubFields .= $tmp852;
                if ($tmp852 =~ m/<subfield code="p">(.*)<\/subfield>/) {
                    my $bc =$1;
                    $bcList->{$bc}=1;
                }

       }
       foreach my $b(keys %$bcList){
           if($bcList->{$b}==0 && $tmp852 ne ""){
               $fixed=1;
               my $f852 =$tmp852;
               $f852 =~ s/<subfield code="p">(.*)<\/subfield>/<subfield code="p">$b<\/subfield>/;
               $newSubFields .=$f852 ;
           }
       }
      if($fixed){
            $count++;
            $xml =~ s/[\s]*<\/record>/$newSubFields\n<\/record>/;
            mxml_update($dbh, {rid=>$rid,marcXml=>$xml});
            print logFile "$rid\n";
      }
    }
    $sth->finish;
   print "total:$count\n";
   close logFile;

# Codes end.

exit 0;


sub getBbList{
    my ($dbh,$rid) =@_;
    my $bcList={};
    my $sth =$dbh->prepare("select barcode from opl_item where rid= ? && barcode not regexp '^___'");
    $sth->execute($rid);
    while(my $bc=$sth->fetchrow_array){
        $bcList->{$bc}=0;
    }
    return $bcList;

}

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 getRecXml{
    my ($zdbDir,$rid) =@_;
    my $content="";
    if (-f "$zdbDir/$rid.xml"){
        open REC_DEL, "<$zdbDir/$rid.xml";
        while (<REC_DEL>) {
            $content .= $_;
        }
        close REC_DEL;
    }
    return $content;
}
#////////////////////////////////////////////////////////////////////////////
