#!/usr/bin/perl

# for i in /etc/opals/conf/*; do sudo $SCRIPTNAME -c $i; done

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

open FILE, ">>/tmp/opl_category.txt" or die $!;
print FILE "Database: $config->{'db_name'}\n";

my $sql = "select * from opl_category";
my $sth = $dbh->prepare($sql);
$sth->execute();
print FILE  "catid\tcattype\tcatname maxloans maxreserv required  defaultPerm\n";
while (my $c = $sth->fetchrow_hashref()){
    print FILE "$c->{'catid'}\t$c->{'cattype'}\t$c->{'catname'} $c->{'maxloans'} $c->{'maxreserv'} $c->{'required'} $c->{'defaultPerm'}\n";
}
close FILE;

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