#!/usr/bin/env python
# getAPLocation v2.0 by Geordie
# you no longer need to specify the cookie here. just run as normal, and it will ask you to login.

def doLogin(username,password):
	params = urllib.urlencode({'credential_0': username, 'credential_1': password, 'noexpire':'on'})
	headers = {"Accept-Encoding":"text/plain"}
	conn = httplib.HTTPConnection("wigle.net")
	conn.request("POST", "/gps/gps/main/login/", params, headers)
	reply = conn.getresponse()
	if (reply.status == 302):
		print "Successful login - do this again in 10 years"
		data = reply.getheader("Set-Cookie").split(";")
		return data[0]
	if (reply.status == 200):
		print "Login failed - check username/password"
		return ""

def save_cookie(cookie):
	try:
		f = open('wigle_cookie', 'w')
		f.write(cookie)
		f.close()
	except:
		print "Error saving cookie! Check that wigle_cookie can be created and/or written to."

def load_cookie():
	try:
		f = open('wigle_cookie', 'r')
		cookie = f.read()
		f.close()
	except:
		print "No cookie file found. This will be created."
		cookie = ""
	return cookie

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

if (len(sys.argv) == 1):
	print "Usage:\n%s <bssid> : lat/long for BSSID\n%s login : login to WiGLE." % (sys.argv[0], sys.argv[0])
	sys.exit()

if (sys.argv[1] == "login"):
	cookie = ""
	while (cookie == ""):
		username = raw_input("Username: ")
		password = getpass.getpass("Password: ")
		cookie = doLogin(username,password)
		save_cookie(cookie)
	sys.exit()
		

cookie = load_cookie()

if (cookie == ""): # we have no cookie
	print "No cookie set. Attempting to generate one."
	while (cookie == ""):
		username = raw_input("Username: ")
		password = getpass.getpass("Password: ")
		cookie = doLogin(username,password)
		save_cookie(cookie)

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:
	if ((data.count("Search Results:")) == 0):
		print("Page received was not the search results. Check cookies, captive portals etc.\nTo get a new cookie, run \"%s login\"." % sys.argv[0])
	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."