#!/usr/bin/env python

# Code almost completely taken from https://code.google.com/p/geolocate-cli/
# by 2010 Francis Markham
#
# Turned into simple python module and command by Paul Wouters <pwouters@redhat.com>
#
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License as published by 
# the Free Software Foundation, either version 3 of the License, or 
# (at your option) any later version. This program is distributed in the 
# hope that it will be useful, but WITHOUT ANY WARRANTY; without 
# even the implied warranty of MERCHANTABILITY or FITNESS FOR 
# A PARTICULAR PURPOSE. See the GNU General Public License 
# for more details. You should have received a copy of the GNU General 
# Public License along with this program. If not, see <http://www.gnu.org/licenses/>. 

import sys
import argparse
import urllib2
import geome

def main():
	parser = argparse.ArgumentParser(description="geome verbose or not")
	parser.add_argument('-q', '--quiet', action='store_true',help='quiet mode, only prints lat and long')
	parser.add_argument('-s', '--silent', action='store_true',help='quiet mode, only prints lat and long')
	parser.add_argument('-a', '--address', action='store_true',help='print human readable address')
	parser.add_argument('-j', '--json', action='store_true',help='print json string returned')
	parser.add_argument('-r', '--rawjson', action='store_true',help='print full raw json string returned')
	parser.add_argument('-c', '--country', action='store_true',help='print country name')
	parser.add_argument('-C', '--city', action='store_true',help='print city name')
	parser.add_argument('-n', '--neighborhood', action='store_true',help='print neighborhood name')
	parser.add_argument('-i', '--iso', action='store_true',help='print country iso code')
	parser.add_argument('-v', '--version', action='store_true',help='show version and exit')
	parser.add_argument('-k', '--apikey', metavar="apikey", action='store', help='specify google api key')
	parser.add_argument('-K', '--keyshow', action='store_true', help='show google api key used')
	args = parser.parse_args(sys.argv[1:])

	num = 0
	for arg in (args.country, args.city, args.iso, args.address, args.rawjson, args.neighborhood):
		if arg:
			num += 1
	if num > 1:
		sys.exit("geome: You can only specify one output type")

	if args.apikey:
		if args.keyshow:
			print "Google API key:%s"%args.apikey
		geome.apikey(args.apikey)
	else:
		if args.keyshow:
			mykey = geome.apikey()
			if mykey:
				print "Google API key:%s"%mykey
			else:
				print "No Google API key found."

	if args.version:
		sys.exit("geome: version 2.0")
	if args.silent or args.quiet:
		verbose = False
	else:
		verbose = True
	# check if we are online, bail out early if blocked by hotpost or else the timeout can be very long
	try:
		fp = urllib2.urlopen("http://fedoraproject.org/static/hotspot.txt",timeout=5)
	except:
		sys.stderr.write("Failed to connect - network error")
		sys.exit(1)

	desturl = fp.geturl()
	content = fp.readline() 
	if desturl == "http://fedoraproject.org/static/hotspot.txt" and content == "OK\n":
		# clean internet, proceed
		if args.address:
			loc = geome.my_address()
		elif args.city:
			loc = geome.my_city()
		elif args.iso:
			loc = geome.my_country_iso()
		elif args.country:
			loc = geome.my_country()
		elif args.neighborhood:
			loc = geome.my_neighborhood()
		elif args.json:
			loc = geome.location()
		elif args.rawjson:
			loc = geome.json_latlong()
		else:
			loc = geome.location()
			try:
				print "%s,%s"%(loc["location"]["lat"], loc["location"]["lng"])
			except:
				sys.stderr.write("Failure - bad url or api key?\n")
				sys.exit(3)
			sys.exit()
		print loc
	else:
		sys.stderr.write("captive portal preventing location gathering - authenticate first\n")
		sys.exit(2)


if __name__ == "__main__":
        main()

