#! /bin/sh

# Test representation of a table with URLs

TMP_DIR="${TMPDIR}"

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

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

BASENAME=$(basename $0 .pl)

#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

# 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

mkdir ${TMP_DIR}/website
mkdir ${TMP_DIR}/website/cgi-bin
mkdir ${TMP_DIR}/tests

cp ${INPUT_SCRIPT} ${TMP_DIR}/website/cgi-bin

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

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_FILE} "create table parent(id int, a int, b int)"
sqlite3 ${TMP_DB_FILE} "create table child(id int, parent_a int, parent_b int, FOREIGN KEY(parent_a, parent_b) REFERENCES parent(a, b))"
sqlite3 ${TMP_DB_FILE} "insert into parent values (1, 2, 3)"
sqlite3 ${TMP_DB_FILE} "insert into parent values (4, 5, 6)"
sqlite3 ${TMP_DB_FILE} "insert into parent values (7, 8, 9)"
sqlite3 ${TMP_DB_FILE} "insert into child values (1, 2, 3)"
sqlite3 ${TMP_DB_FILE} "insert into child values (2, 2, 4)"
sqlite3 ${TMP_DB_FILE} "insert into child values (3, 1, 3)"

export REQUEST_URI='/~saulius/restful/website/samples.db/child/1'
export HTTP_HOST=test.domain.net
export REQUEST_METHOD=post
export REMOTE_USER=writer

${INPUT_SCRIPT} \
    column%3Achild%3A0.parent=4 \
    column%3Achild%3A0.parent_a=8 \
    column%3Achild%3A0.parent_b=8 \
    Update=Update

sqlite3 -nullvalue NULL ${TMP_DB_FILE} "select * from child"

# Go back to the original directory before deleting the temporary one:
cd - > /dev/null

# Temporary directory will be deleted by the trap.
