#!/bin/sh

TESTS="\
    CalDAV/delete.xml \
    CalDAV/vtodos.xml \
"

CALYPSO_PID=
DAEMON_LOG="${0}_daemon.log"

set -e

cleanup ()
{
   [ -z $CALYPSO_PID ] || kill $CALYPSO_PID
   rm --preserve-root -rf $WORKDIR
}

run_calypso ()
{
    # Run the server
    calypso -g >$DAEMON_LOG 2>&1 &
    CALYPSO_PID=$!
    sleep 2
}

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

# Initial calendars
CALENDARS="\
           $WORKDIR/calendars/__uids__/user01/calendar/       \
           $WORKDIR/calendars/__uids__/user01/tasks/          \
          "

for d in $CALENDARS; do
  mkdir -p $d
  git init $d
done

# config
git config --global user.email "calypso@example.com"
git config --global user.name "Cal Ypso"

export CALYPSO_CONFIG=$WORKDIR/config
cat > $CALYPSO_CONFIG <<EOF
[server]
ssl=false

[acl]
type=htpasswd
filename=$WORKDIR/passwd
encryption=plain

[storage]
folder=$WORKDIR/
EOF
echo "user01:user01" > $WORKDIR/passwd

run_calypso

# Run the tests
if ! testcaldav -s $PWD/debian/tests/serverinfo.xml $TESTS; then
    echo "*** Tests failed, daemon log follows:"
    cat $DAEMON_LOG
    exit 1
fi

echo "run: OK"
