#!/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-confroom@example.com"

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"

for N in `seq 1 5` ; do
  SENDER="mailto:person-$N@example.com"
  mkdir -p "$PREFS/$SENDER"
  echo 'Europe/Oslo' > "$PREFS/$SENDER/TZID"
done

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/fb-request-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/fb-request-day.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out1.tmp

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

# Loop until all requests have been satisfied.

while [ ! -e outP1.tmp ] || [ `grep 'PARTSTAT' outP*.tmp | grep 'ACCEPTED' | wc -l` != '5' ] ; do

  # Request free/busy information.

  FBRESULT="outfbP.tmp"
  export SENDER="mailto:person-N@example.com"
  export SENDERADDRESS="person-N@example.com"

    envsubst < "$TEMPLATES/fb-request-group.txt" \
  | tee "infbP.tmp" \
  | "$RESOURCE_SCRIPT" $ARGS 2>> $ERROR \
  | "$SHOWMAIL" 2>> $ERROR \
  > "$FBRESULT"

  # Set the requesters on a race to book with this information.

  seq 1 5 | xargs -P0 -I{} "$THIS_DIR/resource_request.sh" {} "$FBRESULT"
  wait
  echo "Accepted: `grep 'ACCEPTED' outP*.tmp | wc -l`"

done

   [ `grep 'PARTSTAT' outP*.tmp | grep 'ACCEPTED' | wc -l` = '5' ] \
&& echo "Success" \
|| echo "Failed"

  "$RESOURCE_SCRIPT" $ARGS < "$TEMPLATES/fb-request-day.txt" 2>> $ERROR \
| "$SHOWMAIL" \
> out2.tmp

   grep -q 'METHOD:REPLY' out2.tmp \
&& [ `grep '^FREEBUSY' out2.tmp | sort -u | wc -l` = '5' ] \
&& echo "Success" \
|| echo "Failed"
