#! /bin/sh

# Test upload of a CSV file.

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

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

cp ${DB_FILE} ${TMP_DB_FILE}

export REQUEST_URI="/~saulius/restful/website/${TMP_TEST_DB}.db/bibliography"
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 "==="

cat <<EOF > ${TMP_DIR}/bibliography.csv
# This is a comment,,,
id,authors,title,year
5,O. Kitsune,The tale of nine tails,1506
2017,S. Gražulis et al.,RESTful Web script design,2017
EOF

cd ${TMP_DIR}
zip --quiet bibliography.zip bibliography.csv
cd - > /dev/null

(
perl -lne 'print "$_\r"' <<PART1
--------------------------b989696a28305e74
Content-Disposition: form-data; name="csvzipfile"; filename="fill.zip"
Content-Type: application/zip

PART1
cat ${TMP_DIR}/bibliography.zip
echo -r "\r"
perl -lne 'print "$_\r"' <<PART2
--------------------------b989696a28305e74
Content-Disposition: form-data; name="db"

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

bibliography
--------------------------b989696a28305e74--
PART2
) | ${INPUT_SCRIPT}

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

rm -f ${TMP_DB_FILE}
