#! /usr/bin/python3

import sys
import re
import shutil
from urllib.parse import urlparse, urlunparse
from urllib.request import urlopen
from urllib.error import HTTPError

import apt
from aptsources.distro import get_distro

(package_name, package_version, src_package) = sys.argv[1:]

# Find the package in the available archive repositories.  Use a _binary_
# package name and version to locate the appropriate archive.  Then use the
# URI there to look for and find the appropriate binary.
cache = apt.Cache()

package = None
for version in cache[package_name].versions:
    if version.version == package_version:
        package = version
        break

if not package:
    raise KeyError("{0}: package version not found".format(package_name))


pool_parsed = urlparse(package.uri)
distro = get_distro().codename
#distro = 'quantal'
package_dir = "/main/uefi/%s-%s/%s/" % (
    src_package, package.architecture, package_version)

def download(base):
    for pocket in ('-proposed', '-updates', '-security', '', '-backports'):
        dists_parsed = list(pool_parsed)
        dists_parsed[2] = re.sub(r"/pool/.*", "/dists/" + distro + \
            pocket + package_dir + base, dists_parsed[2])
        dists_uri = urlunparse(dists_parsed)

        print("Downloading %s ... " % dists_uri, end='')
        try:
            with urlopen(dists_uri) as dists, open(base, "wb") as out:
                shutil.copyfileobj(dists, out)
        except HTTPError as e:
            if e.code == 404:
                print("not found")
                continue
            raise
        else:
            print("found")
            return True
    return False
    
for base in "flavours", "version":
    if not download(base):
        print('download-signed: {0}: not found'.format(base))
        sys.exit(1)

with open("flavours") as fd:
    for line in fd:
        filename = line.rstrip()
        filename += '.signed'
        if not download(filename):
            print('download-signed: {0}: not found'.format(filename))
            sys.exit(1)
