#!/usr/bin/perl

#binmode(STDOUT, ":utf8");
#use utf8;
use strict;
use DBI;

my $dbh = dbhTarget($ARGV[0]);
if ( !$dbh )
{
    print "Cannot connect to Opals database";
    exit 0;
}

my $sthSystem = $dbh->prepare(<<_STH_);
select  *
from    opl_libSystem
order by sid asc
_STH_
my $sthSchool = $dbh->prepare(<<_STH_);
update  opl_library
set     sysCode=?
where   sysCode=?
_STH_

$sthSystem->execute;
while (my $libSys = $sthSystem->fetchrow_hashref) {
    print "\nSystem => sid: $libSys->{'sid'}\tcode: $libSys->{'code'}\tname: $libSys->{'name'}\n";
    $sthSchool->execute($libSys->{'code'}, $libSys->{'sid'});
}
$sthSchool->finish;
$sthSystem->finish;
exit 0;

###########################################################
sub dbhTarget 
{
    my ($configfile) =@_;
    my ($db_driver, $db_name, $db_host, $db_port, $db_user, $db_password);
#    my $configfile = '';
#    print "Enter the config filename of Opals: ";
#    $configfile = <STDIN>;
    my $cfgTarget = LoadConfig($configfile);
    return if ( !$cfgTarget );

    $db_driver   = $cfgTarget->{'db_driver'} || 'mysql';
    $db_name     = $cfgTarget->{'db_name'};
    $db_host     = $cfgTarget->{'db_host'};
    $db_port     = $cfgTarget->{'db_port'}   || '3306';
    $db_user     = $cfgTarget->{'db_user'};
    $db_password = $cfgTarget->{'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) = @_;
    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;
}
