#! /bin/sh

# Test update of a record.

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_DB_FILE=${TMP_DB_DIR}/bibliography.db
TMP_DB_META=${TMP_DB_DIR}/bibliography_restful.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
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_FILE} <<END
    create table bibliography (
        id integer primary key autoincrement,
        title text,
        doi text
    );
END
sqlite3 ${TMP_DB_META} < sql/metatables.sql
sqlite3 ${TMP_DB_META} <<END
    insert into description (id, dbname, dbtable, dbcolumn, coltype)
        values (300, 'bibliography.db', 'bibliography', 'doi', 'resource');
    insert into resolver (column_id, is_primary, baseurl)
        values (300, 1, 'https://doi.org/');
END


export REQUEST_URI="/~saulius/restful/website/bibliography.db/bibliography"
export HTTP_HOST=test.domain.net
export REQUEST_METHOD=POST
export CONTENT_TYPE="multipart/form-data; boundary=boundary"
export REMOTE_USER=writer

tools/scripts/multipart-form-data boundary <<EOF |
column:bibliography:0.title=Book+I
column:bibliography:0.doi=10.1002/(SICI)1099-0682(199802)1998:2<283::AID-EJIC283>3.0.CO;2-L
db=bibliography.db
Save=Save
EOF
${INPUT_SCRIPT}

sqlite3 -nullvalue NULL ${TMP_DB_FILE} 'select * from bibliography order by id';

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