#!/bin/bash

# Test package that computes default database settings

TMP_DIR="${TMPDIR}"

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

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

BASENAME=$(basename $0 .pm)

#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}/test4fk.db"
TMP_DB_META="${TMP_DIR}/restful.db"
TMP_DB_MAIN_ABS=$(cd $(dirname ${TMP_DB_MAIN}); pwd)/test4fk.db

sqlite3 ${TMP_DB_MAIN} < tests/inputs/samples-r92.sql

sqlite3 ${TMP_DB_META} < sql/metatables.sql
sqlite3 ${TMP_DB_META} < tests/inputs/samples-metadata-r92.sql
sqlite3 ${TMP_DB_META} "update description set dbname = '${TMP_DB_MAIN_ABS}'"

sqlite3 ${TMP_DB_META} <<END
    insert into validation_regex (id, regex)
        values (1, '\d{2,7}-\d{2}-\d');
    insert into validation_regex (id, regex)
        values (2, '(\d{3}-){2}-[\dX]');
    insert into description (id, dbname, dbtable, dbcolumn, coltype, validation_regex_id)
        values (300, '${TMP_DB_MAIN_ABS}', 'compound', 'cas_number', 'extkey', 1);
    insert into description (id, dbname, dbtable, dbcolumn, coltype, validation_regex_id)
        values (301, '${TMP_DB_MAIN_ABS}', 'compound', 'ec_number', 'extkey', 2);
    insert into resolver (column_id, is_primary, baseurl)
        values (300, 1, 'http://www.commonchemistry.org/ChemicalDetail.aspx?ref=');
END

export TMP_DB_MAIN

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

use strict;
use warnings;
use utf8;

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();

# A CAS number of L-epinephrine
print $db->get_unique_key_column( 'compound', '51-43-4' ), "\n";
# An EC number of dexamethasone
print $db->get_unique_key_column( 'compound', '200-003-9' ), "\n";
END

# Temporary directory will be deleted by the trap.
