#!/bin/bash

# Usage:
#
#   debian/test/queries                - compare results with reference file
#   debian/test/queries <dest>         - write results as reference to <dest>

set -e

tmp=$(mktemp -d ${AUTOPKGTEST_TMP:+-p ${AUTOPKGTEST_TMP}})
trap "{ rm -rf $tmp; }" EXIT

if [ -z "$1" ]
then
  results="$tmp/results"
  ref="debian/tests/data/reference"
else
  results="$1"
fi

base="$tmp/calypso"
config="$base/config"
collection="private/test"
store="$base/calendars"
url="http://127.0.0.1:5233/$collection"
data="debian/tests/data/contacts.vcf"
timeout="timeout 15"

# Make a calypso CardDAV store

mkdir -p $store/$collection

cat > $config <<- EOF
[storage]
folder = $store
EOF

export CALYPSO_CONFIG="$config"

pushd $store/$collection
git init -b master
git config user.email "autopkgtest@example.com"
git config user.name "Autopktest User"
cat > .calypso-collection <<- EOF
[collection]
is-calendar = 0
is-addressbook = 1
EOF
git add .calypso-collection
git commit -m 'new addressbook'
popd

calypso -g -i $collection $data 2>&1

# Start Calypso CardDAV server

coproc CALYPSO { exec calypso -H 127.0.0.1 -fg 2>&1; }
trap "{ echo Killing calypso on error >&2; kill %coproc; }" ERR
eval "exec 9<&${CALYPSO[0]}"

# Synchronise on HTTP listener
#   FIXME: calypso prints the 'Starting' message *before* actually starting
#          so this isn't actually safe, but it will err on the side of failing
while [[ "${REPLY%% HTTP*}" != "Starting" ]]
do
  read -u 9
  echo "CALYPSO: $REPLY"
done

# Keep printing the logs for diagnostics and to prevent backpressure
sed 's,^,CALYPSO: ,g' <&9 &

# Run tests, concatenating results
$timeout mcds -c null -u "$url" King | tee $results
$timeout mcds -c null -u "$url" Kin2 | tee -a $results

kill %coproc
trap - ERR

if [ -n "$ref" ]
then
  diff -u $ref $results >&2
fi
