#!/usr/bin/perl -w
=item
command to update all the sites:

for i in `ls /etc/opals/conf/`; do cp -p /www/opals/script/fixXmlCharReturn /tmp/urt; perl -pi -e "s/_MY_SITE_/$i/" /tmp/urt; sudo /tmp/urt; done

=cut
use lib '/www/opals/module';
use Opals::Context("/etc/opals/conf/_MY_SITE_");
#use Opals::Context("/etc/opals/conf/scsd_snm");

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

my $dbh = Opals::Context->dbh();
END {
    if ($dbh) {
        $dbh->disconnect();
    }
}

$| = 1;

my $zdbDir = Opals::Context->config('zRoot') .'/'
           . Opals::Context->config('zPort') .'/'
           . 'record' .'/'
           . Opals::Context->config('zDatabase');

my $indexDir;
my $attTbl;
my $query_insert ;

my $sth = $dbh->prepare(<<_SQL_);

select  distinct(rid)
from    opl_item where  barcode not regexp '^\_\_\_' && available =1 
order by rid asc 
_SQL_
    $sth->execute;
    my $dir;
    while (my ($rid) = $sth->fetchrow_array) {
        fixXmlRecord($zdbDir, $rid);
    }
    $sth->finish;



# 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 fixXmlRecord {
    my ($zdbDir, $rid) = @_;

    my $record = '';
    my $dir = ceil($rid/1000);
    if (! -f "$zdbDir/$dir/$rid.xml") {
        print "ERROR: $zdbDir/$dir/$rid.xml: not found.\n";
        return;
    }

    #print "$rid\n";
    #return;
    my $fixed=0;
    open MARCXML, "<$zdbDir/$dir/$rid.xml";
    while (<MARCXML>) {
            $record .=$_;
    }
    close MARCXML;

    if($record =~ s/\n/ /g){
            $fixed=1;
            print "$rid\n";
    }
    if($fixed){
        open  RECORD, ">$zdbDir/$dir/$rid.xml";
        #open  RECORD, ">/tmp/$rid.xml";
        print RECORD $record;
        close RECORD;
        print "$zdbDir/$dir/$rid.xml" ,"\n";

    }
    
}

sub escapeXml {
    my ($str) = @_;
    $str =~ s/&/&amp;/g;
    $str =~ s/&amp;(#[\d]+|amp|quot|gt|lt|apos);/&$1;/g;
    return $str;
}

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




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