#!/bin/sh

set -e

#CURDIR=$(realpath $(dirname "$0"))
CURDIR=$(dirname "$0")

cleanup() {
	[ ! -f "$WORKDIR/pid" ] || kill $(cat "$WORKDIR/pid")
	rm --preserve-root -rf $WORKDIR
}

WORKDIR=$(mktemp -d)
trap cleanup 0 INT QUIT ABRT PIPE TERM

# config
cat <<EOF > $WORKDIR/config
[auth]
type=htpasswd
htpasswd_filename=$WORKDIR/passwd
htpasswd_encryption=plain

[storage]
type=filesystem
filesystem_folder=$WORKDIR/

[logging]
config=$WORKDIR/logging
EOF

# logging
cat <<EOF > $WORKDIR/logging
[loggers]
keys = root

[handlers]
keys = file

[formatters]
keys = simple

[logger_root]
level = DEBUG
handlers = file

[handler_file]
class = FileHandler
args = ('$WORKDIR/log',)
formatter = simple

[formatter_simple]
format = %(message)s
EOF

# accounts
echo > "$WORKDIR/passwd"
for u in $(seq 1 9); do
	echo "user0$u:user0$u" >> "$WORKDIR/passwd"
done
for u in $(seq 10 40); do
	echo "user$u:user$u" >> "$WORKDIR/passwd"
done

# testsuite
mkdir -p "$CURDIR/testsuite/data"
ln --symbolic --force --target-directory="$CURDIR/testsuite/data" \
	/usr/share/caldavtester/Resource
ln --symbolic --force --target-directory="$CURDIR/testsuite" \
	/usr/share/caldavtester/scripts/tests
sed \
	-e 's/{hostname}/localhost/' \
	-e 's/{nonsslport}/5232/' \
	-e 's/{sslport}/0/' \
	-e 's/{authtype}/basic/' \
	/usr/share/caldavtester/scripts/server/serverinfo-template.xml \
	> "$CURDIR/testsuite/serverinfo.xml"

# Run the server
radicale --no-ssl --daemon --pid="$WORKDIR/pid" --config="$WORKDIR/config"
sleep 2

# Run the tests
#testcaldav -s $CURDIR/serverinfo.xml $TESTS
python /usr/share/caldavtester/testcaldav.py --basedir "$CURDIR/testsuite" --print-details-onfail "$@" \
	|| {
		echo "BEGIN Radicale log"
		cat "$WORKDIR/log"
		echo "END Radicale log"
		[ -n "$FAIL_OK" ] || false
	}

rm -rf "$CURDIR/testsuite"

echo "run: OK"
