""" almalinux download """
import os

from virt.qemutest.distro.core import FetchDistroCore

class FetchAlmaCloud(FetchDistroCore):
    """ class for almalinux cloud image download """

    alma = "https://repo.almalinux.org/almalinux/"

    def __init__(self, mirror = None, arch = None):
        super().__init__(arch)
        self.mirror = mirror
        if mirror is None:
            self.mirror = self.alma

    def baseurl(self, release):
        return f'{self.mirror}{release}/cloud/{self.arch}/images/'

    def image_id(self, release):
        return f'almalinux-{release}-{self.arch}-cloud'

    @staticmethod
    def checksum_find_alma(url, pattern):
        """ find file (and sha256) by downloading CHECKSUM file """

        print(f'# fetch {url} ...')
        req = FetchDistroCore.request(url, False)
        if req is None:
            raise RuntimeError('request failed')
        matches = {}
        for line in req.text.splitlines():
            if not pattern in line:
                continue
            if 'latest' in line:
                continue
            if 'ext4' in line:
                continue
            (checksum, filename) = line.split()
            matches[filename] = checksum
        if len(matches) == 0:
            return (None, None)
        latest = sorted(matches.keys(), reverse = True)[0]
        return (latest, matches[latest])

    def find_image(self, release, pattern):
        checksum = f'{self.baseurl(release)}CHECKSUM'
        return self.checksum_find_alma(checksum, pattern)

    def fetch_image(self, release = 10, pattern = 'GenericCloud', imgdir = 'distro'):
        print(f'# ----- almalinux {release} ({pattern}) -----')
        (latest, checksum) = self.find_image(release, pattern)
        if latest is None:
            raise RuntimeError('image not found')
        url = f'{self.baseurl(release)}{latest}'
        out = f'{imgdir}/{latest}'
        os.makedirs(imgdir, exist_ok = True)
        self.fetch_image_checksum(url, out, checksum)
        self.index_update(imgdir, self.image_id(release), latest, checksum,
                          url = url)
