""" alpine linux download """
import os
import yaml
import requests

from virt.qemutest.distro.core import FetchDistroCore

class FetchAlpineIso(FetchDistroCore):
    """ class for alpine linux iso download """

    mirror = 'https://dl-cdn.alpinelinux.org/alpine/latest-stable/releases/'

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

    def baseurl(self):
        return f'{self.mirror}{self.arch}/'

    def image_id(self, flavor):
        return f'{flavor}-{self.arch}-liveiso'

    def find_image(self, flavor):
        req = requests.get(f'{self.baseurl()}latest-releases.yaml', timeout = 60)
        req.raise_for_status()
        entries = yaml.load(req.text, Loader=yaml.SafeLoader)
        for e in entries:
            if e.get('flavor') != flavor:
                continue
            filename = e.get('file')
            checksum = e.get('sha256')
            return (filename, checksum)
        raise RuntimeError(f'alpine flavor {flavor} not found')

    def fetch_image(self, flavor = 'alpine-virt', imgdir = 'distro'):
        print(f'# ----- {flavor} -----')
        (latest, checksum) = self.find_image(flavor)
        url = f'{self.baseurl()}{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(flavor), latest, checksum)

    def iso_url(self, flavor = 'alpine-virt'):
        (latest, checksum) = self.find_image(flavor)
        url = f'{self.baseurl()}{latest}'
        return url
