#!/usr/bin/perl 
use lib("/www/opals/module");

=item
command to update all the sites:

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

=cut

use Opals::Context('/etc/opals/conf/cu_chl');
#use Opals::Context("/etc/opals/conf/_MY_SITE_");
use strict;
use Opals::Constant; 
use Date::Calc::Object qw(
    :all
);
use Digest::SHA qw(
    sha1_hex
    sha512_hex
);

use POSIX qw(
    ceil
    floor
);
use MARC::Record;
use MARC::Field;
use MARC::File::XML;
use MARC::File::USMARC;
use Opals::Marc::Record;
use Opals::MarcXml qw(
   mxml_update 
    
);

use MARC::Record;
use MARC::Field;
use MARC::File::XML;

use CGI;
use DBI;

my $dbh = Opals::Context->dbh();
my $zRoot   = Opals::Context->config('zRoot');
my $zPort   = Opals::Context->config('zPort');
my $zDatabase = Opals::Context->config('zDatabase');

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

select   distinct rid 
from     opl_item  
_SQL_

    $sth->execute;
    my $count =0;
    while (my ($rid) = $sth->fetchrow_array) {
        if($rid){
            print "$rid\n";
            cp092at0852h($dbh,$rid);
        }
    }
    $sth->finish;


############################################################
sub cp092at0852h{
    my($dbh,$rid,$prefix) =@_;

    my $marcXml = getMarcXml($rid);  
    return if ($marcXml eq '');
    my $marc = Opals::Marc::Record::newFromXml($marcXml);
    my $sf092a =$marc->subfield( '092', 'a');
    if($sf092a && $sf092a ne ''){
        update852h($marc,$sf092a);
        #saveRecord($rid,$marc);
        my $xml = MARC::File::XML::record($marc);
        mxml_update($dbh,{rid=>$rid,marcXml=>$xml});
    }
 }
############################################################

sub update852h{
    my($marc,$data)=@_;
    my @fields = $marc->field('852');
    foreach my $f852(@fields){
        if(defined $f852->subfield('h')){
            $f852->update('h' => $data );
        }
        else{
            $f852->add_subfields( 'h' => $data );
        }
    }
}

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

sub getMarcXml{
    my ($rid)=@_;
    my $dir  = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);
    my $xml = '';
    if (-f "$dir/$rid.xml") {
        open  RECORD, "<$dir/$rid.xml";
        while (<RECORD>) {
            $xml .= $_;
        }
        close RECORD;
    }
    return $xml;
}

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

sub saveRecord{
    my ($rid,$marc)=@_;
    my $dir  = "$zRoot/$zPort/record/$zDatabase/" . ceil($rid/1000);
    if (-f "$dir/$rid.xml") {
        my $xml = MARC::File::XML::record($marc);
        #open  RECORD, ">$dir/$rid.xml";
        print  $xml;
        #close RECORD;
    }
}

