#!/usr/bin/perl -w

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

my %options = ();
getopts("c:d:l:",\%options);
my $configFile = $options{c};
my $date       = $options{d};
my $location   = $options{l};
if (!$configFile || ! -f $configFile ||
    !$date       || $date !~ m/^[\d]{4}-[\d]{2}-[\d]{2}$/ ||
    !$location   || ! -d $location) {
    print "Usage: $0 -c CONFIG_FILE -d DEL_DATE[YYYY-MM-DD] -l XML_REC_LOCATION\n";
    exit 1;
}

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

$| = 1;
# Codes start...

my $out = '/tmp/del-' . $config->{'db_name'} . '-' . $date . '.xml';
get_deleted_records_items($dbh, $date, $location, $out);


# 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 get_deleted_records_items {
    my ($dbh, $date, $location, $out) = @_;

    my $rid_barcode = getDeletedRecItem($dbh, $date);
    writeFile($rid_barcode, $location, $out);
}
############################################################


sub getDeletedRecItem {
    my ($dbh, $date) = @_;

    my $sth = $dbh->prepare(<<_SQL_);
select  rid, barcode
from    opl_item
where   available = 0
     && barcode regexp '^___'
     && substr(barcode, 4) not regexp '^DUP_'
     && substr(modDate, 1, 10) = ?
_SQL_

    $sth->execute($date);
    my $rid_barcode;
    while (my ($rid, $bc) = $sth->fetchrow_array()) {
        $bc =~ s/(^___|_[\d]{3}$)//g;

        $rid_barcode->{$rid}->{$bc} = 1;
    }
    $sth->finish;

    return $rid_barcode;
}
############################################################


sub writeFile {
    my ($rid_barcode, $location, $out) = @_;

    my @rids = keys %{$rid_barcode};
    my ($rCount, $iCount) = (scalar(@rids), 0);

    open OUT, ">$out";
    print OUT "<collection>\n";

    my ($file, $rec, $bc_list, $line, $in852, $del_bc, $item_xml, $bc);
    foreach my $rid (sort {$a <=> $b} @rids) {
        $file = $location . '/' . ceil($rid/1000) . '/' . $rid . '.xml';
        if (! -r $file) {
            print "Cannot read file '$file'.\n";
            next;
        }

        $rec = $rid_barcode->{$rid};
        $bc_list = "\t" . join("\t", keys %{$rec}) . "\t";
        $iCount += scalar(keys %{$rec});

        ($del_bc, $item_xml, $in852) = (0, '', 0);

        open FILE, "<$file";
        while ($line = <FILE>) {
            if ($line =~ m/(subfield code="-"|<\?xml version="1.0" encoding="UTF-8"\?>)/) {
                next;
            }

            if ($line !~ m/<leader>[\w ]{24}<\/leader>/) {
                $line =~ s/<leader>.+<\/leader>/<leader>00000cam  2200241   4500<\/leader>/;
            }

            if ($line =~ m/<datafield tag="852" ind1="/) {
                $in852 = 1;
                $del_bc = 0;
                $item_xml = '';
            }
            if ($in852 == 1) {
                $item_xml .= $line;

                if ($line =~ m/<subfield code="p">(.+)<\/subfield>/) {
                    $bc = $1;
                    if ($bc_list =~ m/\t$bc\t/) {
                        $del_bc = 1;
                    }
                }

                if ($line =~ m/<\/datafield>/) {
                    $in852 = 0;
                    if ($del_bc == 1) {
                        print OUT $item_xml;
                    }

                    next;
                }
            }
            else {
                print OUT $line;
            }
        }
        close FILE;

        print "$rid:$bc_list\n";
    }

    print OUT "</collection>\n";
    close OUT;

    print <<_STR_;
Deleted records:    $rCount
Deleted items:      $iCount
_STR_
}
