#!/usr/bin/perl 
use lib("/www/opals/module");
use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);

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);
$dbh->do("update opl_lost set ondate=now() where ondate is null");
my $sth_odl=$dbh->prepare(<<_SQL_);
insert into opl_odl set idloan=?, type='lost' ,ondate=? 
_SQL_

my $sth_transaction=$dbh->prepare(<<_SQL_);
insert into opl_transactions set uid= ? , date=?, description='lost'
_SQL_

my $sth_transDetail=$dbh->prepare(<<_SQL_);
insert into opl_transactiondetail set tid=?, odl_id=? , 
responsible=1,materials='book', note='transfer lost items from the past'
_SQL_
my $sth=$dbh->prepare(<<_SQL_);
    select l.uid,l.idloan,l2.ondate 
    from opl_loan l inner join opl_lost l2
    on l.idloan=l2.idloan 
_SQL_
$sth->execute(); 
while(my ($uid,$idloan,$ondate)=$sth->fetchrow_array){
    
    $sth_odl->execute($idloan,$ondate);
    my $odlId=$dbh->{'mysql_insertid'};
    $sth_transaction->execute($uid,$ondate);
       
    my $tid=$dbh->{'mysql_insertid'};
    $sth_transDetail->execute($tid,$odlId);
    
    
}

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


exit 0;

