#!/usr/bin/python

# Copyright (C) 2011 Canonical Ltd., Daniel Holbach
#
# ##################################################################
#
# 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; version 3.
#
# 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.
#
# See file /usr/share/common-licenses/GPL-3 for more details.
#
# ##################################################################
#
#
# harvest - grabs information about development opportunities from
#           harvest.ubuntu.com
#
#
# Daniel Holbach
# (c) 2011 Canonical

from optparse import OptionParser
import urllib2
import json
import sys

BASE_URL = "http://harvest.ubuntu.com/"
URL_STUB = BASE_URL + "opportunities/json/"

def opportunity_summary(data):
    l = []
    for key in filter(lambda a: a != "total", data.keys()):
        l += ["%s (%s)" % (key, data[key])]
    return ", ".join(l)

def main():
    usage = "usage: %prog source-package-name"
    opt_parser = OptionParser(usage)
    (options, args) = opt_parser.parse_args()
    if not args:
        opt_parser.print_help()
        sys.exit(1)
    pkg = sys.argv[1]
    url = URL_STUB + pkg.strip()
    try:
        sock = urllib2.urlopen(url)
    except IOError, e:
        try:
            urllib2.urlopen(BASE_URL)
        except urllib2.URLError, _e:
            print >> sys.stderr, "Harvest is down."
            sys.exit(1)
        print "There is no information in Harvest about package '%s'." % pkg
        sys.exit(1)
    response = sock.read()
    sock.close()
    data = json.loads(response)
    print >> sys.stdout, \
"""%s has %s opportunities: %s
Find out more: %sopportunities/package/%s""" % (pkg,
                              data["total"],
                              opportunity_summary(data),
                              BASE_URL,
                              pkg)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print >> sys.stderr, "Aborted."
        sys.exit(1)