#!/usr/bin/perl
# vim:ts=4:noet:

use strict;
use DBI;
use FileHandle;
use Getopt::Long;
use OpenSRF::EX qw/:try/;
use OpenSRF::Utils::Logger qw/$logger/;
use OpenSRF::System;
use OpenSRF::AppSession;
use OpenSRF::Utils::SettingsClient;

use open ':utf8';

binmode(STDIN, ':utf8');
binmode(STDOUT, ':utf8');

$| = 1;

my ($config, $delim, $after,$deleted) = ('@sysconfdir@/opensrf_core.xml', ' | ');

GetOptions(
	"after=s"	=> \$after,
	"bootstrap=s"	=> \$config,
	"delimiter=s"	=> \$delim,
	"include-deleted"	=> \$deleted,
);

OpenSRF::System->bootstrap_client( config_file => $config );

# XXX Get this stuff from the settings server
my $sc = OpenSRF::Utils::SettingsClient->new;
my $db_driver = $sc->config_value( reporter => setup => database => 'driver' );
my $db_host = $sc->config_value( reporter => setup => database => 'host' );
my $db_port = $sc->config_value( reporter => setup => database => 'port' );
my $db_name = $sc->config_value( reporter => setup => database => 'db' );
if (!$db_name) {
    $db_name = $sc->config_value( reporter => setup => database => 'name' );
    print STDERR "WARN: <database><name> is a deprecated setting for database name. For future compatibility, you should use <database><db> instead." if $db_name; 
}
my $db_user = $sc->config_value( reporter => setup => database => 'user' );
my $db_pw = $sc->config_value( reporter => setup => database => 'pw' );

die "Unable to retrieve database connection information from the settings server" unless ($db_driver && $db_host && $db_port && $db_name && $db_user);

my $dsn = "dbi:" . $db_driver . ":dbname=" . $db_name .';host=' . $db_host . ';port=' . $db_port;

my $dbh = DBI->connect($dsn,$db_user,$db_pw, {AutoCommit => 1, pg_enable_utf8 => 1, RaiseError => 1});

my $SQL = 'SELECT id FROM biblio.record_entry WHERE id > 0';
$SQL .= " AND edit_date > '$after'" if ($after);
$SQL .= " AND deleted IS FALSE" if (!$deleted);

my $ids = $dbh->selectcol_arrayref($SQL);

$SQL = <<'SQL';
SELECT  id,
        tcn_source,
        tcn_value,
        deleted,
        REGEXP_REPLACE(marc, E'\\n','','g') AS marc
  FROM  biblio.record_entry
  WHERE id = ?
SQL

for my $id ( @$ids ) {
    my $row = $dbh->selectrow_hashref( $SQL, {}, $id );
    print "$$row{deleted}$delim$$row{id}$delim$$row{tcn_source}$delim$$row{tcn_value}$delim$$row{marc}\n";
}

