#! /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_BASE=${TMP_TEST_DB}.db
TMP_DB_FILE=${DB_DIR}/${TMP_TEST_DB}.db

cp ${DB_FILE} ${TMP_DB_FILE}

mkdir -p ${TMP_DIR}/tests/inputs

cp tests/inputs/duck.xls ${TMP_DIR}/duck.xls

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 "==="

cd ${TMP_DIR}
zip --quiet duck.zip duck.xls
cd - > /dev/null

(

cat <<PART1
--------------------------b989696a28305e74
Content-Disposition: form-data; name="xlszipfile"; filename="duck.zip"
Content-Type: application/octet-stream

PART1
cat ${TMP_DIR}/duck.zip
echo -r "\r"
cat <<PART2
--------------------------b989696a28305e74
Content-Disposition: form-data; name="db"

${TMP_DB_BASE}
--------------------------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}
