#!/usr/bin/python
# Copyright (c) 2010 Alon Swartz <alon@turnkeylinux.org>
#
# This file is part of Auto-APT-Archive.
#
# Auto-APT-Archive is open source 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.
#
#
# Hub API Notes:
#    - URL: https://hub.turnkeylinux.org/api/geoip/
#    - Responses are returned in application/json format
#
#    aptarchive/<distro>/
#        method: GET
#        fields: 
#        return: apt_archive
#
#    Exceptions:
#        400 APTArchive.InvalidDistro
#
"""Query TurnKey Hub GeoIP service for the closest/best APT package archive

Arguments:
    
    distro      APT package distribution (eg. ubuntu, debian)
"""

import sys
import getopt
import simplejson as json

from pycurl_wrapper import Curl

class Error(Exception):
    pass

def usage(e=None):
    if e:
        print >> sys.stderr, "Error:", e
    print >> sys.stderr, "Syntax: %s <distro>" % sys.argv[0]
    print >> sys.stderr, __doc__
    sys.exit(1)

class API:
    ALL_OK = 200
    CREATED = 201
    DELETED = 204

    @classmethod
    def request(cls, method, url, attrs={}, headers={}):
        c = Curl(url, headers)
        func = getattr(c, method.lower())
        func(attrs)

        if not c.response_code in (cls.ALL_OK, cls.CREATED, cls.DELETED):
            name, description = c.response_data.split(":", 1)

            raise Error(c.response_code, name, description)

        return json.loads(c.response_data)

def get_aptarchive(distro):
    API_URL = 'https://hub.turnkeylinux.org/api/geoip/'
    API_HEADERS = {'Accept': 'application/json'}

    url = API_URL + 'aptarchive/%s/' % distro
    response = API.request('GET', url, headers=API_HEADERS)

    return response['apt_archive']

def main():
    try:
        opts, args = getopt.gnu_getopt(sys.argv[1:], "h", ['help'])
    except getopt.GetoptError, e:
        usage(e)

    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage()

    if not len(sys.argv) == 2:
        usage("Missing argument: distro")

    distro = sys.argv[1]
    if not distro in ('ubuntu', 'debian'):
        usage("Unsupported distribution: %s" % distro)

    print get_aptarchive(distro)

if __name__ == "__main__":
    main()


