#!/usr/bin/perl -w

use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
);

use File::stat;
use Time::localtime;
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);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...

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

my $indexDir;
my $attTbl;
my $query_insert ;
Update_insertTables($dbh);

my $sth = $dbh->prepare(<<_SQL_);
select  rid
from    opl_marcRecord 
order by rid asc  
_SQL_
    $sth->execute;
    my $dir;
    while (my ($rid) = $sth->fetchrow_array) {
        my $xml=getXmlRecord($zdbDir, $rid);
        if($xml){
            updateLeader_008($dbh, $rid,getXmlRecord($zdbDir, $rid));
        }
    }
    $sth->finish;

### RECORDS MODIFIED
my $sth = $dbh->prepare(<<_SQL_);
select  rid
from    opl_marcRecord 
order by rid asc  
_SQL_
    $sth->execute;
    my $dir;
my $sth_update = $dbh->prepare(<<_SQL_);
update opl_marcRecord 
set modDate=?
where rid= ?
_SQL_
my $date="";
    while (my ($rid) = $sth->fetchrow_array) {
        $date =getFileModDate($zdbDir, $rid);
        $sth_update->execute($date,$rid);
        print "$rid: $date\n";        
    }
    $sth->finish;

#Update opl_item set modDate field
     $sth_update = <<_STH_;
update  opl_item
set     modDate= dateImport
_STH_
    my $sth = $dbh->prepare($sth_update);
    $sth->execute();


# 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 updateLeader_008 {
   my ($dbh, $rid, $xml) = @_;
   my ($leader, $cf_008)=('','');
   my $sth = $dbh->prepare(<<_SQL_);
update opl_marcRecord
set leader=?, cf_008=?
where rid =?
_SQL_
   
    # Extract leader
    if ($xml =~ s/[\s]*<leader>([\w ]{24})<\/leader>//) {
        $leader=$1;
    }
    
    # Extract control field -- 008
    if($xml =~ s/[\s]*<controlfield tag="008">(.*)<\/controlfield>//){
        $cf_008=$1;
    }
    $sth->execute($leader,$cf_008,$rid);
 
}

sub fixOpenHour{
    my ($dbh)=@_;
    my $sth = $dbh->prepare(<<_SQL_);
select count(*) from opl_openHours where open1<>'' || open2 <>'';
_SQL_
$sth->execute();
my ($c)=$sth->fetchrow_array();
    if($c==0){
         $sth = $dbh->prepare(<<_SQL_);
         update opl_openHours
         set open1='7:00-4:00'
         where weekday in(1,2,3,4,5)
         
_SQL_
    $sth->execute();

    }

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

sub Update_insertTables{
    my($dbh)=@_;

    $dbh->do("delete from opl_preference where var='fdrtax'");
    $dbh->do("alter table opl_marcRecord add leader varchar(24) default null, add cf_008 varchar(40) default null");
    $dbh->do("alter table opl_marcRecord add modDate datetime default '0000-00-00 00:00:00' ");
    
    $dbh->do("alter table opl_item add modDate timestamp");

    $dbh->do("alter table opl_marcExport change eType eType enum('date','rid','all','modDate_r','modDate_h','ridList_r','ridList_h')");
    $dbh->do("alter table opl_marcExport add ridList text ");
    $dbh->do("create index index1 on opl_itemstatus(barcode,ondate,status)");
    $dbh->do("create index index1 on opl_marcRecord(leader,cf_008,modDate)");
    
    fixOpenHour($dbh);
    
     $dbh->do("DROP TABLE IF EXISTS opl_transactions");
     $dbh->do("CREATE TABLE  `opl_transactions` (
  `tid` int(10) unsigned NOT NULL auto_increment,
  `uid` int(10) unsigned NOT NULL default '0',
  `amount` float(10,2) NOT NULL default '0.00',
  `balance` float(10,2) NOT NULL default '0.00',
  `date` datetime NOT NULL default '0000-00-00 00:00:00',
  `description` varchar(50) default NULL,
  PRIMARY KEY  (`tid`),
  UNIQUE KEY `tid` (`tid`),
  KEY `tid_2` (`tid`,`uid`,`date`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1");
     

     $dbh->do("DROP TABLE IF EXISTS opl_transactiondetail");
     $dbh->do("CREATE TABLE `opl_transactiondetail` (
  `tid` int(10) unsigned default '0',
  `odl_id` int(10) unsigned NOT NULL,
  `responsible` varchar(64) default '',
  `materials` set('book','video','DVD','reserve material') default 'book',
  `rate` float(10,2) default '0.00',
  `overdueDays` tinyint(3) unsigned default '0',
  `fineAmount` float(10,2) default '0.00',
  `forgivenAmount` float(10,2) default '0.00',
  `amount` float(10,2) default '0.00',
  `taxes` float(10,2) default '0.00',
  `note` varchar(254) default '',
  KEY `NewIndex` (`tid`,`odl_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ");
     
     $dbh->do("DROP TABLE IF EXISTS opl_taxcalcdetail");
     $dbh->do("CREATE TABLE `opl_taxcalcdetail` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `tid` int(10) unsigned NOT NULL default '0',
  `taxName` varchar(64) NOT NULL default '0',
  `taxRate` float(10,2) NOT NULL default '0.00',
  `taxBase` set('basic','taxontax') NOT NULL default 'basic',
  `taxableAmount` float(10,2) NOT NULL default '0.00',
  `tax` float(10,2) NOT NULL default '0.00',
  PRIMARY KEY  (`id`),
  KEY `NewIndex` (`tid`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1");
     
     $dbh->do("DROP TABLE IF EXISTS opl_odl");
     $dbh->do("CREATE TABLE `opl_odl` (
  `odl_id` int(10) unsigned NOT NULL auto_increment,
  `idloan` int(10) unsigned default '0',
  `type` set('overdue','lost','damaged') default 'overdue',
  `days_overdue` tinyint(3) unsigned default '0',
  `ondate` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`odl_id`),
  KEY `NewIndex` (`odl_id`,`idloan`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1 ");
     
     $dbh->do("DROP TABLE IF EXISTS opl_taxes");
     $dbh->do("CREATE TABLE `opl_taxes` (
  `id` tinyint(3) unsigned NOT NULL auto_increment,
  `taxName` varchar(64) default '0',
  `rate` float(10,2) default '0.00',
  `type` set('flat','%') default '%',
  `calFormat` set('basic','taxontax') default 'basic',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1");

     
     $dbh->do("DROP TABLE IF EXISTS opl_fineRate");
     $dbh->do("CREATE TABLE `opl_fineRate` (
  `id` tinyint(3) unsigned NOT NULL auto_increment,
  `fineType` set('overdue','lost','damaged') default 'overdue',
  `material` varchar(128) default 'book',
  `rate` float(10,2) default NULL,
  `max` float(10,2) default '0.00',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=97 DEFAULT CHARSET=latin1");
     
     
     $dbh->do("INSERT into opl_preference (var,val,opt,description) values('defaultSearchPage','0','0|1|2','Default search interface; 0:standard,1:beginner,2:advance') ");
     $dbh->do("INSERT into opl_preference (var,val,opt,description) values('bibTimeclear','5m','string','bibiography time clear') ");
     $dbh->do("INSERT into opl_preference (var,val,opt,description) values('useHolidays','1','0|1','Default 0: System will include holidays as working days in circulation  1: System will exclude holidays  in circulation') ");
        
}
############################################################


sub getFileModDate {
    my ($zdbDir, $rid) = @_;

    my $dateStr = '';
    my $dir = ceil($rid/1000);
    if ( -f "$zdbDir/$dir/$rid.xml") {
        my $file;
        open $file, "<$zdbDir/$dir/$rid.xml";    
        #my($sec,$min,$hour,$day,$month,$year) = localtime();
        my $t= localtime(stat($file)->mtime);
        my ($year,$month,$day,$h,$m,$s) = ($t->year+1900 ,$t->mon+1,$t->mday, $t->hour,$t->min,$t->sec );
        $dateStr =sprintf ("%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$h,$m,$s);
        close $file;
    }
    return $dateStr;
    
}

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