#!/bin/sh

# Replace the following with your ClientLogin auth token
# curl -v 'https://www.google.com/accounts/ClientLogin?accountType=GOOGLE&Email=EMAIL&Passwd=PASSWORD&service=local&source=test'
AUTH="AUTH_TOKEN"

# Create map
curl -v -o map.xml 'http://maps.google.com/maps/feeds/maps/default/full' -H 'Content-Type: application/atom+xml' -H 'Authorization: GoogleLogin auth="'"$AUTH"'"' --data-ascii '<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app">
<title>Test Map</title>
<summary></summary>
<app:control>
<app:draft>yes</app:draft>
</app:control>
</entry>'

# Get map's feature feed URL
mapurl=`cat map.xml | sed -E 's@.*(http://maps.google.com/maps/feeds/features/[a-zA-Z0-9/]*/full).*@\1@'`

# Attempt to post placemark to map
curl -v -o placemark.xml "$mapurl" -H 'Content-Type: application/atom+xml' -H 'Authorization: GoogleLogin auth="'"$AUTH"'"' --data-ascii '<?xml version="1.0" encoding="utf-8"?>
<atom:entry xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
  <atom:title>Original Title</atom:title>
  <atom:content type="application/vnd.google-earth.kml+xml">
    <Placemark>
      <name>Original Title</name>
      <description />
      <Point>
        <coordinates>-123.4567,01.234567,0.0</coordinates>
      </Point>
      <Style/>
    </Placemark>
  </atom:content>
</atom:entry>'

# Get placemark's id
id=`cat placemark.xml | sed -E 's@.*(http://maps.google.com/maps/feeds/features(/[a-zA-Z0-9]{21}){3}).*@\1@'`
edit=`cat placemark.xml | sed -E 's@.*(http://maps.google.com/maps/feeds/features(/[a-zA-Z0-9]{21}){2}/full/[a-zA-Z0-9]{21}).*@\1@'`

# Attempt to batch upload to map
curl -v -o batch.xml "$mapurl/batch" -H 'Content-Type: application/atom+xml' -H 'Authorization: GoogleLogin auth="'"$AUTH"'"' --data-ascii '<?xml version="1.0" encoding="utf-8"?>
<atom:feed xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch">
<atom:entry>
  <batch:operation type="update" />
  <batch:id>1</batch:id>
  <atom:id>'"$id"'</atom:id>
  <atom:link rel="edit" type="application/atom+xml" href="'"$edit"'"/>
  <atom:title>New Title</atom:title>
  <atom:content type="application/vnd.google-earth.kml+xml">
    <Placemark>
      <name>New Title</name>
      <description />
      <Point>
        <coordinates>-12.765432,37.654321,0.0</coordinates>
      </Point>
      <Style/>
    </Placemark>
  </atom:content>
</atom:entry>
</atom:feed>'

# Now list features: Should show a single placemark
curl -v -o features.xml "$mapurl" -H 'Authorization: GoogleLogin auth="'"$AUTH"'"'
cat features.xml | tidy -xml -indent