#!/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_addPubDateSort /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/_MY_SITE_");
#use Opals::Context("/etc/opals/conf/odev");

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...


#my $zdbDir = $config->{'zRoot'} .'/'
#           . $config->{'zPort'} .'/'
#           . 'record' .'/'
#           . $config->{'zDatabase'};

my $zdbDir = Opals::Context->config('zRoot') .'/'
           . Opals::Context->config('zPort') .'/'
           . 'record' .'/'
           . Opals::Context->config('zDatabase');

print "updating site " . "_MY_SITE_" ." \n";           

my $indexDir;
my $attTbl;
my $query_insert ;

my $sth_update = $dbh->prepare("update opl_marcRecord set pubDateSort=? where rid= ?");

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

select  rid,pubDate,deleted
from    opl_marcRecord 
order by rid   
_SQL_
    $sth->execute;
    my $dir;
    while (my ($rid,$pubDate,$deleted) = $sth->fetchrow_array) {
        #print "$rid\n";
        if($deleted){
           if ($pubDate && $pubDate =~ m/([\d]{4})/){
                $pubDate=$1;
           }
           $sth_update->execute($pubDate,$rid);
        }
        else{
            my $xml=getXmlRecord($zdbDir, $rid);
            if($xml){
                updatePublicationInfo($dbh, $rid,$xml);
            }
        }
    }
    $sth_update->finish;
    $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 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 updatePublicationInfo {
   my ($dbh, $rid, $xml) = @_;
   my $sth = $dbh->prepare(<<_SQL_);
update opl_marcRecord
set pubDate=?,pubDateSort= ?,pubPlace=?,pubName=?
where     rid  = ?
_SQL_
   
   my $pubXml="";
  
   if ($xml =~ m/[\s]*(<datafield tag="264" ind1="[\d\ ]" ind2="1">([\s]*<subfield code="[\w\-]">.*<\/subfield>)*[\s]*<\/datafield>)/) {
       $pubXml=$1;
   }
   elsif ($xml =~ m/[\s]*(<datafield tag="260" ind1="[\d\ ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)*[\s]*<\/datafield>)/) {
       $pubXml=$1;
   }


   if( $pubXml ne ""){
       my ($pubDate,$pubDateSort,$pubPlace,$pubName)=('','','','');
       if($pubXml =~ m/<subfield code="a">(.*)<\/subfield>/gi){
           $pubPlace =$1;
       }
       if($pubXml =~ m/<subfield code="b">(.*)<\/subfield>/gi){
           $pubName =$1;
       }
       if($pubXml =~ m/<subfield code="c">(.*)<\/subfield>/gi){
           $pubDate =$1;
       }
       $pubDateSort = $pubDate;
       if($pubDateSort && $pubDateSort =~ m/([\d]{4})/) {
           $pubDateSort = $1;

       }
       $sth->execute($pubDate,$pubDateSort,$pubPlace,$pubName,$rid);
   }


}



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