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

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 $indexDir;
my $attTbl;
my $query_insert ;

#change field modDate from timestamp -> datetime 
# to preserve time stamp
my $rv =$dbh->do(<<_SQL_);
select titleSort from opl_marcRecord limit 1
_SQL_



if(!$rv){
  my $sth =$dbh->prepare(<<_SQL_);
select database() as name
_SQL_
$sth->execute();
 my ($db)=$sth->fetchrow_array();
  print "$db\n";
}

# 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 updateTables{
    my ($dbh)=@_;

 
 $dbh->do("ALTER TABLE `opl_marcRecord` DROP deleted ");
 $dbh->do("ALTER TABLE `opl_marcRecord` DROP titleSort ");
 $dbh->do("ALTER TABLE `opl_marcRecord` DROP INDEX ind_auth");
 $dbh->do("ALTER TABLE `opl_marcRecord` DROP INDEX `ind_titlesort` ");



    $dbh->do(<<_SQL_);
ALTER TABLE `opl_item`
DROP `location`, 
DROP INDEX `ind_location`
_SQL_

#add fields titleSort, deleted and indices to table opl_marcRecord.
$dbh->do(<<_SQL_);
ALTER TABLE `opl_marcRecord` 
ADD `titleSort`  VARCHAR(255) AFTER `title` ,
ADD `deleted` TINYINT UNSIGNED DEFAULT '0' ,
ADD `incomplete` enum('true','false') default 'false' ,
CHANGE `print` `print` set('print','fiction','nonFiction','pro','ref','serial','shortStories') ,
CHANGE `nonPrint` `nonPrint` set('nonPrint','video','audio','multiMedia','cassette','kit','mixedMaterial','notatedMusic','map') , 
ADD FULLTEXT `ind_auth` (`author`)  ,
ADD INDEX `ind_titlesort` (`titleSort`)
_SQL_

#add location field to opl_item 
 
$dbh->do(<<_SQL_);
ALTER TABLE `opl_item` 
ADD `location`  VARCHAR(100) AFTER `price` ,
ADD INDEX `ind_location` (`location`)
_SQL_

#add fields cellphone && incomplete to table opl_user

$dbh->do(<<_SQL_);
ALTER TABLE opl_user
ADD `cellphone` varchar(50),
ADD `incomplete` enum('true','false') default 'false' 
_SQL_


#add field gcellphone to table opl_guadian

$dbh->do(<<_SQL_);
ALTER TABLE opl_guardian
ADD `gcellphone` varchar(50)
_SQL_


#set holding location 
$dbh->do(<<_SQL_);
UPDATE opl_item i inner join opl_itemInfo t on i.barcode =t.barcode 
               && t.sf852Code='c'
SET i.location =t.sf852Data    
_SQL_

#mark deleted record in opl_marcRecord
$dbh->do(<<_SQL_);
UPDATE opl_marcRecord r left outer join opl_item i on i.rid=r.rid && i.barcode not regexp '^\_\_\_' 
SET deleted=1
WHERE  i.rid is null   
_SQL_

}
############################################################


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 updateTitleSortField {
   my ($dbh, $rid, $xml) = @_;
   my $sth = $dbh->prepare(<<_SQL_);
update opl_marcRecord
set titleSort  = ?
where     rid  = ?
_SQL_

   if ($xml =~ m/[\s]*(<datafield tag="245" ind1="[\d ]" ind2="[\d ]">([\s]*<subfield code="[\w\-]">.*<\/subfield>)*[\s]*<\/datafield>)/) {
        my $tmp=$1;
        if($tmp =~ m/<subfield code="\-">(.*)<\/subfield>/){
           my $titleSort=$1;
           $sth->execute($titleSort,$rid);
        }
   }
 
}

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