set -ex
ADMIN=${ADMIN:-admin@mydomain.com}
PASSWORD=${PASSWORD:-mypassword}
USER=${USER:-user@mydomain.com}
AUTH=$(curl --silent -X POST -d accountType=HOSTED_OR_GOOGLE -d Email=$ADMIN -d Passwd=$PASSWORD -d service=cl -d source=curl  https://www.google.com/accounts/ClientLogin | grep Auth | cut -d'=' -f2 | tr -d '\r')
URL=$(curl --silent --head -H "Authorization: GoogleLogin auth=$AUTH" https://www.google.com/calendar/feeds/default/owncalendars/full | grep Location | cut  -d' ' -f2 | tr -d '\r')
cat > /tmp/1 <<EOF
<entry xmlns='http://www.w3.org/2005/Atom'
       xmlns:gd='http://schemas.google.com/g/2005'
       xmlns:gCal='http://schemas.google.com/gCal/2005'>
  <title type='text'>TEST CREATE CALENDAR</title>
  <summary type='text'>TEST CREATE CALENDAR SUMMARY.</summary>
  <gCal:timezone value='America/Los_Angeles'></gCal:timezone>
  <gCal:hidden value='false'></gCal:hidden>
  <gCal:color value='#2952A3'></gCal:color>
  <gd:where rel='' label='' valueString='Oakland'></gd:where>
</entry>
EOF
CALENDAR=$(curl --silent -X POST -H "Authorization: GoogleLogin auth=$AUTH" -H "Content-Type: application/atom+xml" --data-ascii @/tmp/1 $URL | tr -d '\r')
CALENDAR_ACL=$(echo $CALENDAR | xmlstarlet sel -N ns="http://www.w3.org/2005/Atom" -t -m "//ns:link[@rel='http://schemas.google.com/acl/2007#accessControlList']" -m "@href" -v .)
curl -L -H "Authorization: GoogleLogin auth=$AUTH" $CALENDAR_ACL
CALENDAR_ACL_URL=$(curl --silent --head -H "Authorization: GoogleLogin auth=$AUTH" $CALENDAR_ACL | grep Location | cut  -d' ' -f2 | tr -d '\r')
cat > /tmp/2 <<EOF
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gAcl='http://schemas.google.com/acl/2007'>
  <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/acl/2007#accessRule'/>
  <gAcl:role value='http://schemas.google.com/gCal/2005#owner'/>
  <gAcl:scope type='user' value='$USER'/>
</entry>
EOF
curl --silent -X POST -H "Authorization: GoogleLogin auth=$AUTH" -H "Content-Type: application/atom+xml" --data-ascii @/tmp/2 $CALENDAR_ACL_URL | tr -d '\r'
