#! /bin/sh

# Test representation of a table with URLs

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

# Set up the testing "sandbox":
SRC_DB_DIR=db
TMP_DB_DIR=${TMP_DIR}/db
mkdir ${TMP_DB_DIR}

TMP_TEST_DB=samples.db
TMP_DB_FILE=${TMP_DB_DIR}/samples.db
TMP_DB_META=${TMP_DB_DIR}/restful.db
TMP_DB_FILE_ABS=$(cd $(dirname ${TMP_DB_FILE}); pwd)/${TMP_TEST_DB}

sqlite3 ${TMP_DB_FILE} "create table file (id int, filename text, file blob, mimetype text)"
sqlite3 ${TMP_DB_FILE} "insert into file values (1,'test.csv', 'id,authors', 'text/csv')"

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

export TMP_DB_FILE

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

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

use lib 'lib';
use Database;
use RestfulDB::JSON qw( data2json );

binmode( STDOUT, "utf8" );

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

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

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

my $web_base = 'http://solsa.crystallography.net/db/test_samples';

my $data = $db->get_record_descriptions( 'file', { record_id => 1, web_base => $web_base } );
print data2json( $db, $data, 'file', { web_base => $web_base } );
END
json_pp -json_opt canonical,indent

# Temporary directory will be deleted by the trap.
