#! /usr/bin/python3

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

import apt
import apt_pkg

ARCH_TO_EFI_NAME = {
    'amd64': 'x64',
    'i386': 'ia32',
    'arm64': 'aa64',
    'armhf': 'arm',
}
arch = apt_pkg.config['Apt::Architecture']
efi_name = ARCH_TO_EFI_NAME[arch]
cache = apt.Cache()
try:
    fwupd_efi = cache["fwupd-unsigned"].candidate
except KeyError:
    print("fwupd-unsigned not found, falling back to fwupd")
    fwupd_efi = cache["fwupd"].candidate
version = fwupd_efi.version
#drop the epoch from the version as UEFI binary doesn't use it
if ':' in version:
    version = version.split(':')[1]
pool_parsed = urlparse(fwupd_efi.uri)
dists_dir = "/dists/%s/main/uefi/fwupd-%s/%s/" % (
    fwupd_efi.origins[0].archive, fwupd_efi.architecture,
    version)

for base in (
        "fwupd%s.efi.signed" %efi_name,
        "version",
        ):
    dists_parsed = list(pool_parsed)
    dists_parsed[2] = re.sub(r"/pool/.*", dists_dir + base, dists_parsed[2])
    dists_uri = urlunparse(dists_parsed)
    print("Downloading %s ..." % dists_uri)
    with urlopen(dists_uri) as dists, open(base, "wb") as out:
        shutil.copyfileobj(dists, out)
