#!/bin/bash

# Test package that computes default database settings

TMP_DIR="${TMPDIR}"

test -z "${BIN_DIR}" && BIN_DIR=website/cgi-bin

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

BASENAME=$(basename $0 .pm)

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

INPUT_SCRIPT="${BIN_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}/db/test4fk.db"
TMP_DB_META="${TMP_DIR}/db/restful.db"

mkdir $(dirname ${TMP_DB_MAIN})
cp db/test4fk.db ${TMP_DB_MAIN}

ln -s $(pwd)/lib ${TMP_DIR}
ln -s $(pwd)/sql ${TMP_DIR}
ln -s $(pwd)/tools ${TMP_DIR}

mkdir -p ${TMP_DIR}/${BIN_DIR}

cp ${INPUT_SCRIPT} ${TMP_DIR}/${BIN_DIR}

# Change dir to the sandbox and run the test:

cd ${TMP_DIR}

sqlite3 ${TMP_DB_MAIN} "create table related_samples (id integer primary key, sample1_id integer, sample2_id integer)"
sqlite3 ${TMP_DB_MAIN} "insert into related_samples values (1, 1, 2)"
sqlite3 ${TMP_DB_MAIN} "insert into related_samples values (2, 2, 2)"

sqlite3 ${TMP_DB_META} < sql/metatables.sql
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype) values (1, '${TMP_DB_MAIN}', 'sample', 'id', 'id')"
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype, fk_target, relation, visualisation) values (2, '${TMP_DB_MAIN}', 'related_samples', 'sample1_id', 'fk', 1, 'N', 'card')"
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype, fk_target, relation, visualisation) values (3, '${TMP_DB_MAIN}', 'related_samples', 'sample2_id', 'fk', 1, 'N', 'card')"

export REQUEST_URI='/~saulius/restful/website/test4fk.db/sample/1?order=experiment.sample_id%3Aa'
export HTTP_HOST=test.domain.net
export REQUEST_METHOD=get
export REMOTE_USER=tester

${INPUT_SCRIPT}

# Temporary directory will be deleted by the trap.
