#!/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('-v', '--version', action='store_true',help='show version and exit')
	args = parser.parse_args(sys.argv[1:])

	if args.version:
		sys.exit("geome: version 1.4")
	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
		try:
			loc = geome.location()
		except:
			sys.stderr.write("Unexected failure while determing location")
			sys.exit(3)
		if verbose == True:
			print loc
		else:
			print "%s,%s"%(loc["location"]["latitude"], loc["location"]["longitude"])
	else:
		sys.stderr.write("captive portal preventing location gathering - authenticate first")
		sys.exit(2)


if __name__ == "__main__":
        main()

