#!/usr/bin/python

import json
from optparse import OptionParser
import sys

from aptdaemon.piston.scaclient import SoftwareCenterAgentAPI
import piston_mini_client.auth

import gettext
gettext.install("aptdaemon")

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-s", "--server", default="ubuntu-production")
    parser.add_option("-p", "--pkgname")
    (options, args) = parser.parse_args()
    
    # server to use
    if options.server == "ubuntu-production":
        server = "http://software-center.ubuntu.com/api/2.0"
    elif options.server == "ubuntu-staging":
        server = "https://sc.staging.ubuntu.com/api/2.0"
    else:
        raise Exception("Unknown license key server")
    SoftwareCenterAgentAPI.default_service_root = server

    # pkgname
    pkgname = options.pkgname

    # wait for oauth token on stdin
    json_token = sys.stdin.readline()
    token = json.loads(json_token)
       
    # get the data
    auth = piston_mini_client.auth.OAuthAuthorizer(token["token_key"],
                                                   token["token_secret"],
                                                   token["consumer_key"],
                                                   token["consumer_secret"])
    
    api = SoftwareCenterAgentAPI(auth=auth)

    
    try:
        subscriptions =  api.subscriptions_for_me(complete_only=True)
    except piston_mini_client.APIError as e:
        sys.stderr.write(_("Failed to get the license key from "
                           "the server."))
        sys.exit(1)

    license_key = None
    license_key_path = None
    for subscription in subscriptions:
        if subscription.application["package_name"] == pkg_name:
            license_key = subscription.license_key
            license_key_path = subscription.license_key_path

    if license_key and license_key_path:
        sys.stdout.write(license_key_path)
        sys.stdout.write(license_key)
        sys.exit(0)

    # generic error
    sys.stderr.write(_("Failed to get the license key from "
                       "the server."))
    sys.exit(1)
       
