#!/usr/bin/python

#
# ocget -- Get geocaches (in the GPX format) from OpenCaching.pl
#

# default host name, overrided by a command line option
host="opencaching.pl"

import sys
import getopt
import urllib, urllib2

def help():
   print """ocget v0.1
This program is free software, distributed under the terms of the GNU GPL v2.

Usage: ocget [-u hostname] lat,lon maxnumberofgcs [maxdistance]

Downloads up to maxnumberofgcs at a distance of up to maxdistance from lat,lon.

If hostname is not given "opencaching.pl" will be used.

Happy caching!!!
"""

try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "h:d", ["help"])
except getopt.GetoptError:
    # print help information and exit:
    help()
    sys.exit(2)

DEBUG = False

for o, a in opts:
    if o == "-h":
        host = a
    if o == "--help":
        help()
        sys.exit()
    if o == "-d":
        DEBUG = True

if len(args) < 2:
    help()
    sys.exit()

#########################

ll = args[0].split(",")
lat = float(ll[0])
lon = float(ll[1])

if lat >= 0:
    lat_NS="N"
else:
    lat_NS="S"
    lat = -lat
lat_h = int(lat)
lat_min = (lat - lat_h) * 60
if lon >= 0:
    lon_EW="E"
else:
    lon_EW="W"
    lon = -lon
lon_h = int(lon)
lon_min = (lon - lon_h) * 60

if len(args) >= 3:
    maxdist = args[2]
else:
    maxdist = "max"

try:
    maxcaches = int(args[1])
except ValueError:
    maxcaches = 100

params = {
    "latNS": lat_NS,
    "lat_h": lat_h,
    "lat_min": lat_min,
    "lonEW": lon_EW,
    "lon_h": lon_h,
    "lon_min": lon_min,
    "distance": maxdist,
    "unit": "km",
    "count": maxcaches,
    "searchto": "searchbydistance",
    "showresult": "1",
    "sort": "bydistance",
    "output": "gpx",
}

params = urllib.urlencode(params)
url = "http://%s/search.php?%s" % (host, params)

#print >>sys.stderr, "url:", url
#import httplib
#httplib.HTTPConnection.debuglevel = 1

request = urllib2.Request(url)
request.add_header('Accept-encoding', 'gzip')
opener = urllib2.build_opener(urllib2.ProxyHandler, 
                            urllib2.HTTPDefaultErrorHandler, 
                            urllib2.HTTPRedirectHandler, 
                            urllib2.HTTPErrorProcessor)
f = opener.open(request)

if f.headers.get('Content-Encoding') == "gzip":
    import StringIO
    compressedstream = StringIO.StringIO(f.read())
    import gzip
    stream = gzip.GzipFile(fileobj=compressedstream)
    for line in stream:
        sys.stdout.write(line)
elif f.headers.get('Content-Disposition').endswith(".zip\""):
    # workaround for opencaching.de sending ZIP archives
    print >>sys.stderr, "ZIP file detected, trying to uncompress..."
    import StringIO
    compressedstream = StringIO.StringIO(f.read())
    import zipfile
    zip = zipfile.ZipFile(compressedstream, "r")
    first_file = zip.namelist()[0]
    sys.stdout.write(zip.read(first_file))
else:
    for line in f:
        sys.stdout.write(line)

# vi: et sw=4 sts=4
