#!/usr/bin/perl 
use lib("/www/opals/module");
use Opals::Context('/etc/opals/conf/ztest');
#use Opals::Context('/etc/opals/conf/cay_usec');
#use Opals::Context('/etc/opals/conf/cay_ush');

use strict;
use DBI;

use POSIX qw(
    ceil
);
use Opals::MarcXml qw(
    mxml_delete
);
my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }
# Codes start...
deleteRecord($dbh);


# 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 deleteRecord{
    my($dbh)=@_;

  my $sth_rid = $dbh->prepare(<<_STH_);
select distinct i.rid 
from (opl_item i inner join opl_marcRecord m on m.rid=i.rid && mid(m.leader,6,1)='d') 
left outer join opl_loan l on l.barcode=i.barcode where l.barcode is null  && i.barcode not regexp '^\_\_\_'
_STH_

    $sth_rid->execute();

    while(my ($rid)=$sth_rid->fetchrow_array){
        print "$rid\n";
        mxml_delete($dbh,$rid);
    }

        
}

#////////////////////////////////////////////////////////////////////////////
