#!/usr/bin/env python

cookie = "" # find it from your web browser. you must put it here.

try:
	import httplib, urllib, sys, string
except:
	print "You need the following modules:\nhttplib, urllib, sys, string\nInstall them and try again."
	sys.exit()

if (cookie == ""):
	print "You must supply the cookie for wigle login."
	sys.exit()

try:
	netid = sys.argv[1]
	print netid
except:
	print "Usage: %s 00:12:34:56:78:90" % sys.argv[0]
	sys.exit()
	
numberOfOctets = netid.count(":")
if (numberOfOctets != 5):
	print "Invalid BSSID - %i octets found (should have 6)" %  (numberOfOctets + 1)
	sys.exit()
	
length = len(netid)
if (length != 17):
	print "Invalid BSSID - %i characters long (should be 17)" % length
	
try:
	params = urllib.urlencode({'netid': netid})
	headers = {"Accept-Encoding":"text/plain", "Cookie":cookie}
	conn = httplib.HTTPConnection("wigle.net")
	conn.request("POST", "/gps/gps/main/confirmlocquery/", params, headers)
	reply = conn.getresponse()
	data = reply.read()
except:
	print "Error connecting to WiGLE!"
	sys.exit()

try:
	lines=range(data.count("\n"))
	lined_data = data.split("\n")
	for line in lines:
		theLine = lined_data[line]
		if (theLine.find(netid) > 0):
			break

	theLine = str.replace(theLine, """<tr class="useruploaddataeven">""", "")
	theLine = str.replace(theLine, "</tr>", "")
	theLine = str.replace(theLine, "<td>", "")
	theLine = theLine.split("</td>")
	lat = theLine[10]
	lon = theLine[11]

	if(lat[0] == "-"):
		lat = ("%s %s" % (lat[1:], "S"))
	else:
		lat = ("%s %s" % (lat, "N"))
	
	if(lon[0] == "-"):
		lon = ("%s %s" % (lon[1:], "W"))
	else:
		lon = ("%s %s" % (lon, "E"))
	
	print "Latitude: %s, Longitude: %s" % (lat, lon)
except:
	print "No match in WiGLE for specified BSSID"

try:
	conn.close()
except:
	print "Error closing connection."