#!/usr/bin/python
# Copyright (C) 2010 Kees Cook <kees@outflux.net>
# License: GPLv3
# Find location of a MAC address via Google Location Services
# http://code.google.com/p/gears/wiki/GeolocationAPI
import cgi
import sys, urllib2
import simplejson
import pprint

form = cgi.FieldStorage()
if not form or not form.has_key('mac'):
    print "Content-type: text/html"
    print ""
    print "<html><head><title>Boom</title></head><body>"
    print "Enter MAC address to locate: <form><input type=text name=mac length=20></form><br>"
    print '<a href="index.txt">source</a>'
    print "</body></html>"
    sys.exit(0)

try:
    loc_req = { 'version': '1.1.0',
                'request_address': True,
                'address_language': 'en',
                'wifi_towers': [] }
    bssid = form['mac'].value
    loc_req['wifi_towers'] += [{ 'mac_address': bssid.replace(':','-'),
                                 'signal_strength': 1 } ]

    data = simplejson.JSONEncoder().encode(loc_req)

    output = urllib2.urlopen('https://www.google.com/loc/json', data).read()
    output = simplejson.loads(output)

    print "Content-type: text/plain"
    print ""
    pprint.pprint(output)
    if output['location']['accuracy'] >= 22000:
        print "# N.B. Google seems to limit this interface now, unfortunately, so everything looks like it's in Portland (this server's location) now."
        print "# N.B. Accuracy of 22000 or higher seems to indicate unknown location..."
except:
    print "Content-type: text/html"
    print ""
    print "<html><head><title>Boom</title></head><body>"
    print "Sorry, something went wrong"
    print "</body></html>"
