#!/usr/bin/env python
# getAPLocation v4 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, getpass\nInstall them and try again."
	sys.exit()

if (len(sys.argv) == 1):
	print "Usage:\n%s -b <bssid> : lat/long for BSSID\n%s -s <ssid> : lat/long for SSID\n%s -[s|b] <ssid/bssid> -k <filename> : output to KML\n%s login : login to WiGLE." % (sys.argv[0], sys.argv[0],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:
	cmd = sys.argv[1]
	netid = sys.argv[2]
except:
	print "Usage: %s -[s|b] <ssid/bssid> [-k]" % sys.argv[0]
	sys.exit()

try:
	kml = sys.argv[3]
	if (kml == "-k"):
		kmlout = 1
	try:
		kmlname = sys.argv[4]
	except:
		print "You must specify a filename for the KML file"
		sys.exit()
except:
	kmlout = 0
	kmlname = ""

#print "cmd is " + cmd + " netid is " + netid
if (cmd == "-b"):
	ssid = 0
	bssid = 1
	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
		sys.exit()
if (cmd == "-s"):
	ssid = 1
	bssid = 0
	
try:
	headers = {"Accept-Encoding":"text/plain", "Cookie":cookie}
	conn = httplib.HTTPSConnection("wigle.net")
	if (ssid == 1):
		conn.request("GET", ("/gps/gps/GPSDB/confirmquery/?ssid=%s&simple=true" % netid), "", headers)
	if (bssid == 1):
		conn.request("GET", ("/gps/gps/GPSDB/confirmquery/?netid=%s&simple=true" % netid), "", headers)
	if (ssid + bssid == 0):
		sys.exit()
		print "WTF happened!?"
	reply = conn.getresponse()
	data = reply.read()
	#print data
except:
	print "Error connecting to WiGLE!"

if (kmlout == 1):
	f = open(kmlname, 'w')
	f.write("""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
	<name>%s</name>
	<Style id="default+icon=http://maps.google.com/mapfiles/kml/pal3/icon63.png">
		<IconStyle>
			<Icon>
				<href>http://maps.google.com/mapfiles/kml/pal3/icon63.png</href>
			</Icon>
		</IconStyle>
	</Style>""" % kmlname)
	print "Wrote KML header"

try:
	if ((data.count("netid~ssid~comment~name~type~freenet~paynet~firsttime~flags~wep~trilat~trilong~dhcp~lastupdt~channel~active~bcninterval~qos~userfound")) == 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 (line > 0):
			theLine = theLine.split("~")
			
			if (kmlout == 0):
				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)
			if (kmlout == 1):
				f.write("""	<Placemark>
		<name>%s</name>
		<styleUrl>#default+icon=http://maps.google.com/mapfiles/kml/pal3/icon63.png</styleUrl>
		<Point>
			<coordinates>%s,%s,0</coordinates>
		</Point>
	</Placemark>""" % (theLine[1],theLine[11],theLine[10]))
				print "Found %s at %s,%s" % (theLine[1],theLine[11],theLine[10])
except:
	print "Something went wrong parsing WiGLE. Here is what we got:"
	print data
	sys.exit()

if (kmlout == 1):
	f.write("""</Document>
</kml>""")

try:
	conn.close()
except:
	print "Error closing connection. This should not happen."