#!/usr/bin/perl -w

use strict;
use DBI;
use Getopt::Std;
use POSIX qw(
    ceil
    floor
);

my %options = ();
getopts("c::",\%options);
my $configFile = $options{c};
my $bcPrefix="";
my $bcLength=10;

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;

   my $zRoot   =   $config->{'zRoot'};
   my $zPort   =   $config->{'zPort'};
   my $zDatabase = $config->{'zDatabase'};


createCSV_file($dbh);


################################################################################
sub createCSV_file{
    my ($dbh)=@_;
    my $sth = $dbh->prepare("select i.barcode,i.callNumber,m.title,m.author 
                            from opl_item i inner join opl_marcRecord m using(rid) 
                            where barcode not regexp '^\_\_\_'
                            order by callNumber,m.author,m.title");
    $sth->execute();
    my $fmtStr="\"%s\",\"%s\",\"%s\",\"%s\"\n";
    open OUT , ">/tmp/$zDatabase.csv";
    printf OUT $fmtStr,"barcode","callNumber","title","author";
    while( my($bc,$callNumber,$title,$author)=$sth->fetchrow_array){
        $title="" if(!$title);
        $author="" if(!$author);
        $title =~ s/"/""/g;
        $author=~ s/"/""/g;
        printf OUT $fmtStr,$bc,$callNumber,$title,$author;

    }
    close OUT;
    print "CSV file created: /tmp/$zDatabase.csv\n";
}

################################################################################

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