#! /bin/sh

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

TMP_TEST_DB=$(echo tmp${BASENAME}$$ | sed 's/[^-0-9a-zA-Z]//g')

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

SRC_DB_FILE=${SRC_DB_DIR}/test1.db

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

cp ${SRC_DB_FILE} ${TMP_DB_FILE}

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

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

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

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 years (year integer, human_readable text);"
sqlite3 ${TMP_DB_FILE} "insert into years (year, human_readable) values (1984, 'Nineteen Eighty-Four');"
sqlite3 ${TMP_DB_FILE} "insert into years (year, human_readable) values (2000, 'Year Two Thousand');"

sqlite3 ${TMP_DB_META} < sql/metatables.sql
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype, fk_target, relation) values (1, '${TMP_DB_FILE_ABS}', 'bibliography', 'year', 'fk', 2, 'N');"
sqlite3 ${TMP_DB_META} "insert into description (id, dbname, dbtable, dbcolumn, coltype) values (2, '${TMP_DB_FILE_ABS}', 'years', 'year', 'id');"

export REQUEST_URI="/~saulius/restful/website/bibliography?db=${TMP_DB_BASE}"
export QUERY_STRING=$(basename ${REQUEST_URI} | perl -pe 's/^.*?\?//; s/\d+\.db$/.db/')
export HTTP_HOST=test.domain.net
export REQUEST_METHOD=post
export REMOTE_USER=writer

{
    sqlite3 -nullvalue NULL ${TMP_DB_FILE} 'select * from bibliography order by id';
    sqlite3 -nullvalue NULL ${TMP_DB_FILE} 'select * from years order by year';
    sqlite3 -nullvalue NULL ${TMP_DB_META} 'select * from description order by id';
} \
    | sed "s:$(pwd):/cwd:"

echo "==="

${INPUT_SCRIPT} \
    db=${TMP_DB_BASE} \
    action=template \
    | perl -lpe 's/(tmpnewpl)[^\.]+/$1/g'

# Change back to the original directory before deleting the TMP_DIR:
cd - > /dev/null

# TMP_DIR directory will be deleted by the trap.
