#!/usr/bin/perl

use strict;
use DBI;
use Getopt::Std;

my %options = ();
getopts("c:i:",\%options);
my $configFile = $options{c};
my $interval = $options{i};
if (!$configFile || ! -f $configFile || !$interval) {
    print "Usage: $0 -c CONFIG_FILE -i DATE_INTERVAL\n";
    exit 1;
}

my $config = loadConfig($configFile);
my $dbh = makeConnection($config);
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;
# Codes start...
print "Fixing vetoed imports on $config->{'db_name'}...";
fix_vetoedImports($dbh, $interval);
print " done\n";

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


sub fix_vetoedImports {
    my ($dbh, $dateInterval) = @_;

    my $sql = <<_SQL_;
update  opl_marcImport
set     countProcessed = 0
where   countProcessed = countTotal
     && countImported = 0
     && countMerged = 0
     && status = 'accepted'
     && date(dateUpload) >= date(now() - interval $dateInterval day)
_SQL_

    $dbh->do($sql);
}
