#!/usr/bin/perl

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

my $sth_itc = $dbh->prepare(<<_STH_);
select  *
from    opl_itemTypeChange
where   cReplaced = 0
_STH_

my $sth_ii = $dbh->prepare(<<_STH_);
update  opl_itemInfo
set     sf852Data = ?
where   sf852Code = '3' &&
        sf852Data = ?
_STH_

my $sth_i = $dbh->prepare(<<_STH_);
update  opl_item
set     typeId = ?
where   typeId = ?
_STH_

my $sth_itc_update = $dbh->prepare(<<_STH_);
update  opl_itemTypeChange
set     cReplaced = ?
where   cid = ?
_STH_


$sth_itc->execute || return;
while (my $itc = $sth_itc->fetchrow_hashref) {
    #print "$itc->{'cid'}\t$itc->{'oldTypeId'}\t$itc->{'newTypeId'}\t$itc->{'cReplaced'}\n";
    $sth_ii->execute($itc->{'newTypeId'}, $itc->{'oldTypeId'});
    $sth_i->execute($itc->{'newTypeId'}, $itc->{'oldTypeId'});
    $sth_itc_update->execute($itc->{'cTotal'}, $itc->{'cid'});
}
$sth_itc->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;
} 
############################################################
