#!/bin/sh

THIS_DIR=`dirname $0`

TEMPLATES="$THIS_DIR/templates"
RESOURCE_SCRIPT="$THIS_DIR/../imip_resource.py"
SHOWMAIL="$THIS_DIR/../tools/showmail.py"
STORE=/tmp/store
STATIC=/tmp/static
PREFS=/tmp/prefs
ARGS="-S $STORE -P $STATIC -p $PREFS -d"
USER="mailto:resource-room-sauna@example.com"
FBFILE="$STORE/$USER/freebusy"
FBOFFERFILE="$STORE/$USER/freebusy-offers"
TAB=`printf '\t'`

ERROR=err.tmp

rm -r $STORE
rm -r $STATIC
rm -r $PREFS
rm $ERROR
rm out*.tmp

mkdir -p "$PREFS/$USER"
echo 'Europe/Oslo' > "$PREFS/$USER/TZID"
echo 'share' > "$PREFS/$USER/freebusy_sharing"
echo '10,12,14,16,18:0,15,30,45' > "$PREFS/$USER/permitted_times"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/fb-request-sauna-all.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out0.tmp

   grep -q 'METHOD:REPLY' out0.tmp \
&& ! grep -q '^FREEBUSY' out0.tmp \
&& echo "Success" \
|| echo "Failed"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/event-request-sauna-bad.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out2.tmp

   grep -q 'METHOD:COUNTER' out2.tmp \
&& grep -q 'DTSTART;TZID=Europe/Oslo.*:20141126T161500' out2.tmp \
&& echo "Success" \
|| echo "Failed"

   ! [ -e "$FBFILE" ] \
|| ! grep -q "^20141126T151500Z${TAB}20141126T170000Z" "$FBFILE" \
&& echo "Success" \
|| echo "Failed"

   grep -q "^20141126T151500Z${TAB}20141126T170000Z" "$FBOFFERFILE" \
&& echo "Success" \
|| echo "Failed"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/fb-request-sauna-all.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out3.tmp

   grep -q 'METHOD:REPLY' out3.tmp \
&& ! grep -q 'FREEBUSY;FBTYPE=BUSY:20141126T151000Z/20141126T160000Z' out3.tmp \
&& ! grep -q 'FREEBUSY;FBTYPE=BUSY:20141126T151500Z/20141126T160000Z' out3.tmp \
&& echo "Success" \
|| echo "Failed"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/event-request-sauna-good.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out4.tmp

   grep -q 'METHOD:REPLY' out4.tmp \
&& grep -q 'ATTENDEE;PARTSTAT=ACCEPTED' out4.tmp \
&& echo "Success" \
|| echo "Failed"

   grep -q "^20141126T150000Z${TAB}20141126T151500Z" "$FBFILE" \
&& echo "Success" \
|| echo "Failed"

   ! grep -q "^20141126T150000Z${TAB}20141126T151500Z" "$FBOFFERFILE" \
&& ! grep -q "^20141126T151500Z${TAB}20141126T170000Z" "$FBOFFERFILE" \
&& echo "Success" \
|| echo "Failed"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/fb-request-sauna-all.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out6.tmp

   grep -q 'METHOD:REPLY' out6.tmp \
&& grep -q 'FREEBUSY;FBTYPE=BUSY:20141126T150000Z/20141126T151500Z' out6.tmp \
&& echo "Success" \
|| echo "Failed"
