# This class generate the swu file needed by swupdate
# This should not be used directly but via coreos-image.bbclass

# This is made to work with our default boot flow, so it depends on the output
# of coreos-image-uki.bbclass. Other boot flow are not supported by CoreOS.

# Swupdate image generation
# ==============================================================================

IMAGE_FSTYPES:append = " ext4.zst"
python () {
    image = d.getVar('IMAGE_BASENAME')
    d.setVarFlag("SWUPDATE_IMAGES_FSTYPES", image, ".ext4.zst")
}

inherit swupdate-image

# Ensure than variable used in the sw-description files are watched for change
do_swuimage[vardeps] += "COREOS_KERNEL_FILENAME EFIBOOTGUARD_TIMEOUT EFIDIR EFI_BOOT_IMAGE COREOS_EFIBOOTGUARD_FILENAME"
do_swuimage[deptask] += "do_bundle_uki"

COREOS_EFIBOOTGUARD_NAME ?= "efibootguard${EFI_ARCH}"
COREOS_EFIBOOTGUARD_EXT ?= ".efi"
COREOS_EFIBOOTGUARD_FILENAME = "${COREOS_EFIBOOTGUARD_NAME}${COREOS_EFIBOOTGUARD_EXT}"

SWUPDATE_IMAGES += "${COREOS_KERNEL_NAME} ${COREOS_EFIBOOTGUARD_NAME}"

python () {
    kernel = d.getVar('COREOS_KERNEL_NAME')
    kernelext = d.getVar('COREOS_KERNEL_EXT')
    d.setVarFlag("SWUPDATE_IMAGES_FSTYPES", kernel, kernelext)

    efibootguard = d.getVar('COREOS_EFIBOOTGUARD_NAME')
    efibootguardext = d.getVar('COREOS_EFIBOOTGUARD_EXT')
    d.setVarFlag("SWUPDATE_IMAGES_FSTYPES", efibootguard, efibootguardext)
}

FILESEXTRAPATHS:append := ":${COREOS_ROOT}/layers/meta-belden-coreos/files"

# Space seperated list of extension points
COREOS_SWUPDATE_EXTENDS_FOR ??= ""

def coreos_swupdate_extends(d, s, key):
    """
    Extends the swupdate for each extension points defined by COREOS_SWUPDATE_EXTENDS_FOR
    """
    extends_for = d.getVar('COREOS_SWUPDATE_EXTENDS_FOR', True).replace("-", "_").split()

    def kv_to_sw_description(kv):
        swdescr = ",{\n"
        for key, value in kv.items():
            swdescr += f'{key} = "{value}";\n'
        swdescr += "}\n"
        return swdescr

    text = ""

    # BSP and Distro can extends the swupdate by implementing some python 
    # function that return a list of dictionary.
    for extension_point in extends_for:
        try:
            kv_list = globals()[f"coreos_swupdate_extends_{key}_for_{extension_point}"](d,s)
        except KeyError:
            # Don't fail if the extension is not implemented
            pass
        else:
            for kv in kv_list:
                text += kv_to_sw_description(kv)

    return text

# Signature support
inherit coreos-efi-secureboot
SWUPDATE_SIGNING = "CMS"
SWUPDATE_CMS_KEY  = "${COREOS_EFI_SECUREBOOT_KEYDIR}/swupdate.key"
SWUPDATE_CMS_CERT = "${COREOS_EFI_SECUREBOOT_KEYDIR}/swupdate.crt"

COREOS_IMAGE_SWUPDATE_EXTRACLASSES ?= ""
inherit ${COREOS_IMAGE_SWUPDATE_EXTRACLASSES}
