#! /bin/sh

# Test upload of a CSV file.

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

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

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

INPUT_SCRIPT="${BIN_DIR}/${SCRIPT_BASE}"

#END DEPEND--------------------------------------------------------------------

set -ue
## set -x

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

DB_DIR=db
DB_FILE=${DB_DIR}/test1.db
TMP_DB_FILE=${DB_DIR}/${TMP_TEST_DB}.db

# 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_DB_FILE}'" EXIT
trap "exit 1" HUP INT QUIT TERM

cp ${DB_FILE} ${TMP_DB_FILE}

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

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

echo "==="

${INPUT_SCRIPT} <<EOF
--------------------------b989696a28305e74
Content-Disposition: form-data; name="csvfile"; filename="fi
ll.csv"
Content-Type: application/octet-stream

# This is a comment,,
authors,title,year
Saulius Gražulis,Opus Magnum vol. 1,2017
Saulius Gražulis,Opus Magnum vol. 2,2017
Saulius Gražulis,Opus Magnum vol. 3,2017
Saulius Gražulis,Opus Magnum vol. 4,2017
Saulius Gražulis,Opus Magnum vol. 5,2017
Saulius Gražulis,Opus Magnum vol. 6,2017
Saulius Gražulis,Opus Magnum vol. 7,2017
Saulius Gražulis,Opus Magnum vol. 8,2017
Saulius Gražulis,Opus Magnum vol. 9,2017
Saulius Gražulis,Opus Magnum vol. 10,2017
Saulius Gražulis,Opus Magnum vol. 11,2017
Saulius Gražulis,Opus Magnum vol. 12,2017

--------------------------b989696a28305e74
Content-Disposition: form-data; name="db"

${TMP_TEST_DB}.db
--------------------------b989696a28305e74
Content-Disposition: form-data; name="table"

bibliography
--------------------------b989696a28305e74--
EOF

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

# Temporary directory will be deleted by the trap.
