#!/usr/bin/perl -w

use strict;
use DBI;
use Getopt::Std;

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

# Export using hit list of bar codes
$dbh->do(<<_SQL_);
alter
table   opl_marcExport
change  eType eType enum(
            'date',
            'rid',
            'all',
            'modDate_r',
            'modDate_h',
            'ridList_r',
            'ridList_h',
            'hitlist') default NULL
_SQL_

$dbh->do(<<_SQL_);
CREATE TABLE IF NOT EXISTS `opl_ridBcdHitlistExport` (
  `eid` int(10) unsigned default '0',
  `rid` int(10) unsigned default '0',
  `barcode` varchar(50) default '0'
) ENGINE=MyISAM DEFAULT CHARSET=latin1
_SQL_
#/Export using hit list of bar codes

# Text book management
$dbh->do("ALTER TABLE `opl_loan` add `type` VARCHAR(50) DEFAULT NULL");

my ($count) = $dbh->selectrow_array(<<_SQL_);
select  count(*)
from    opl_preference
where   var = 'textbookMgmnt'
_SQL_
if (!$count) {
    $dbh->do(<<_SQL_);
insert
into    opl_preference
set     var = 'textbookMgmnt',
        val = '0',
        opt = '0|1',
        description = 'Enable Textbook management module'
_SQL_
}
#/Text book management

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