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

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

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

use strict;
use DBI;
#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 $sth = $dbh->prepare(<<_SQL_);
select distinct rid 
from opl_item
where  available =1
order by rid  
_SQL_


    $sth->execute;
    my $dir;
    while (my ($rid) = $sth->fetchrow_array) {
        my $xml=getXmlRecord($zdbDir, $rid);
        if($xml){
            mxml_updateItemInfo($dbh, $xml);
        }
    }
    
    $sth->finish;

# Codes end.

exit 0;
############################################################
sub getXmlRecord{
    my ($zdbDir, $rid) = @_;

    my $record = '';
    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>) {
        $record .= $_;
    }
    close MARCXML;
    return $record;
}
#####################################################
sub mxml_updateItemInfo {
    my ($dbh, $marcxml) = @_;
#print "$marcxml\n";
    my $sth_remove = $dbh->prepare(<<_STH_);
delete from opl_itemInfo
where   barcode = ?
_STH_

    my $sth = $dbh->prepare(<<_STH_);
insert into opl_itemInfo
set barcode    = ?,
    sf852Code  = ?,
    sf852Data  = ?
_STH_

    while ($marcxml =~ s/([\s]*<datafield tag="852" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)*[\s]*<\/datafield>)//) {
        my $f852 = $1;
        my @sf852;
        my $barcode;
        while ($f852 =~ s/<subfield code="([\w])">(.*)<\/subfield>//) {
            my ($code, $data) = ($1, $2);
            if ($code eq 'p') {
                $barcode = $data;
                print "$barcode\n";
                #$barcode =~ s/[^\w]//g;
            }
            else {
                push @sf852, [$code, $data] if ($code && defined $data);
            }
        }

        $sth_remove->execute($barcode);
        foreach my $sf (@sf852) {
            $sth->execute($barcode, $sf->[0], $sf->[1]);
        }
    }
    $sth_remove->finish;
    $sth->finish;
}


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