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

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 @orCond = (
        {3 => 'textbook%' }   ,
        {k => 'textbook%' }
    );
    my $ridList = libCollection_getRIdList($dbh, \@orCond);
    my $count = 0;
    foreach my $rid (@{$ridList}){
        my $xml =getRecXml($zdbDir . "/" . ceil($rid/1000), $rid);
        if($xml eq ""){
            my $dir =$zdbDir ."/" .ceil($rid/1000) ."/$rid.xml";
            print "$dir - $rid \n";
            $count ++; 
        }
    }
    print "$count\n";



# Codes end.

exit 0;




sub libCollection_getRIdList {
    my ($dbh, $orCond) = @_;
    my @rIdList = ();
    my @bindVal = ();
    my $sql = "select distinct i.rid from opl_item i inner join opl_itemInfo f using(barcode) 
                    inner join opl_marcRecord m on m.rid=i.rid " ;

    my $sql_where = "";       
    foreach my $c (@{$orCond}){
        $sql_where .= " || " if ( $sql_where ne "");
        foreach my $sfc (keys %{$c}){
            $sql_where .= " ( f.sf852Code = ? && f.sf852Data  like ?  ) " ;
            push (@bindVal, ($sfc,$c->{$sfc}));
        }
    }
                    

    my $sql_order = ' order by i.rid'; 
    $sql .=  ' where ' . $sql_where . $sql_order;

    my $sth = $dbh->prepare($sql);
    $sth->execute(@bindVal);
    while (my $rid = $sth->fetchrow_array){
            push @rIdList, $rid;
    }
    $sth->finish;
    return \@rIdList;
}




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;
}
#////////////////////////////////////////////////////////////////////////////
