#!/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"

ERROR=err.tmp

export N=$1
export START=20141126T090000
export END=20141126T100000
export SENDERADDRESS="person-$N@example.com"
export SENDER="mailto:person-$N@example.com"

# Exit if a previous result indicates acceptance of a request.

   [ -e "outP${N}.tmp" ] \
&& `grep 'PARTSTAT' "outP${N}.tmp" | grep -q 'ACCEPTED'` \
&& exit 0

FBRESULT=$2

# Find the end of a busy period or use the initial start.

FBSTART=`grep 'FREEBUSY' "$FBRESULT" | grep -v 'VFREEBUSY' | tail -n 1 | cut -d: -f2 | cut -d/ -f2 | tr -d '\\r'`
FBEND=`python "$THIS_DIR/next_time.py" "$FBSTART" 09 16`
START=${FBSTART:-$START}
END=${FBEND:-$END}

echo "Try for $N with $START and $END..."

# Request a resource on behalf of a numbered person identity.

  envsubst < "$TEMPLATES/event-request-group.txt" \
| tee "inP${N}.tmp" \
| "$RESOURCE_SCRIPT" $ARGS 2>> $ERROR \
| "$SHOWMAIL" 2>> $ERROR \
> "outP${N}.tmp"
