#! /bin/sh

# Test update of a record.

TMP_DIR="${TMPDIR}"

test -z "${LIB_DIR}" && LIB_DIR=lib

SCRIPT_BASE=`basename $0 | sed "s/_[0-9]*\.sh$//"`

BASENAME=$(basename $0 .pl)

#BEGIN DEPEND------------------------------------------------------------------

INPUT_SCRIPT="${LIB_DIR}/${SCRIPT_BASE}"

#END DEPEND--------------------------------------------------------------------

set -ue
## set -x

test -z "${TMP_DIR}" && TMP_DIR="/tmp"
TMP_DIR="${TMP_DIR}/tmp-${BASENAME}-$$"
mkdir "${TMP_DIR}"

# To make the trap portable between bash and dash, we need to trap
# "signal" 0 ("EXIT") and rely on it for the cleanup:
## trap "rm -rf '${TMP_DIR}'" 0 1 2 3 15
trap "rm -rf '${TMP_DIR}'" EXIT
trap "exit 1" HUP INT QUIT TERM

TMP_DB_MAIN="${TMP_DIR}/test1.db"
TMP_DB_META="${TMP_DIR}/restful.db"
TMP_DB_MAIN_ABS=$(cd $(dirname ${TMP_DB_MAIN}); pwd)/test1.db

cp db/test1.db ${TMP_DB_MAIN}

sqlite3 ${TMP_DB_META} < sql/metatables.sql
sqlite3 ${TMP_DB_META} "insert into description (dbname, dbtable, dbcolumn, coltype) values ('${TMP_DB_MAIN_ABS}', 'bibliography', 'year', 'id')"

export TMP_DB_MAIN

perl <<'END'
#!/usr/bin/perl

use strict;
use warnings;
use utf8;
use Data::Dumper;

use lib 'lib';
use Database;

binmode( STDOUT, "utf8" );

$Data::Dumper::Sortkeys = 1;
$Data::Dumper::Indent   = 1;

my $db_settings = {
    content_db => {
        DB => $ENV{TMP_DB_MAIN},
        engine => 'SQLite'            
    }
};

my $db = Database->new( $db_settings );
$db->connect();

my $comparison = OPTIMADE::Filter::Comparison->new( '=' );
$comparison->left( OPTIMADE::Filter::Property->new( 'bibliography', 'year' ) );
$comparison->right( 1505 );
my $filter = Database::Filter->new_from_tree( $comparison );

print Dumper $db->get_record_descriptions( 'bibliography', { record_id => 1505 } );
print Dumper $db->get_record_descriptions( 'bibliography', { filter => $filter } );
END

# Temporary directory will be deleted by the trap.
