""" RHEL download """
import os

from virt.qemutest.distro.core import FetchDistroCore, FetchNetinst

def rhel_toplevel(release, nightly):
    major = release.split('.')[0]
    group = 'rel-eng'
    subdir = 'BaseOS'
    if nightly:
        group = 'nightly'
    if int(major) < 8:
        subdir = 'Server'
    return f'rhel-{major}/{group}/RHEL-{major}/latest-RHEL-{release}/compose/{subdir}'

def rhel_rpmrepos(mainrepo):
    rpmrepos = None
    if 'BaseOS' in mainrepo:
        # rhel8+
        rpmrepos = { 'baseos'    : mainrepo,
                     'appstream' : mainrepo.replace('BaseOS', 'AppStream') }
    if 'Server' in mainrepo:
        # rhel7
        rpmrepos = { 'server' : mainrepo }
    return rpmrepos

class FetchRHELCloud(FetchDistroCore):
    """ class for rhel cloud image download """

    def __init__(self, mirror, arch = None, nightly = False):
        super().__init__(arch)
        self.mirror = mirror
        self.nightly = nightly

    def baseurl(self, release):
        toplevel = rhel_toplevel(release, self.nightly)
        return f'{self.mirror}/{toplevel}/{self.arch}/images/'

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

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

    def fetch_image(self, release, pattern = 'guest-image', imgdir = 'distro'):
        print(f'# ----- rhel {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)

        mainrepo = url.rsplit('/', 2)[0] + '/os/'
        rpmrepos = rhel_rpmrepos(mainrepo)

        self.index_update(imgdir, self.image_id(release), latest, checksum,
                          url = url, rpmrepos = rpmrepos)

class FetchRHELInstall(FetchDistroCore):
    """ class for rhel full install iso download """

    def __init__(self, mirror, arch = None, nightly = False):
        super().__init__(arch)
        self.mirror = mirror
        self.nightly = nightly

    def baseurl(self, release):
        toplevel = rhel_toplevel(release, self.nightly)
        return f'{self.mirror}/{toplevel}/{self.arch}/iso/'

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

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

    def fetch_image(self, release, pattern = 'dvd', imgdir = 'distro'):
        print(f'# ----- rhel {release} ({pattern}) -----')
        (latest, checksum) = self.find_image(release, pattern)
        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)

class FetchRHELNetinst(FetchNetinst):
    """ class for rhel netinst iso download """

    nightly = False

    def __init__(self, mirror, arch = None, nightly = False):
        super().__init__(mirror, arch)
        self.nightly = nightly

    def rpmrepos(self, booturl):
        mainrepo = booturl.removesuffix('images/boot.iso')
        return rhel_rpmrepos(mainrepo)

    def baseurl(self, release):
        toplevel = rhel_toplevel(release, self.nightly)
        return f'{self.mirror}/{toplevel}/{self.arch}/os/'
