# This class generate the UKI kernel needed by WIC and by swupdate
# This class should not be used directly, as it's ihnerited by
# the coreos-image class

require conf/image-uefi.conf
inherit kernel-artifact-names
inherit coreos-efi-sbsign

# Output file name
# ==============================================================================

COREOS_KERNEL_EXT ??= ".efi"
COREOS_KERNEL0_NAME ??= "kernel0-${MACHINE}"
COREOS_KERNEL1_NAME ??= "kernel1-${MACHINE}"
COREOS_KERNEL0_FILENAME ??= "${COREOS_KERNEL0_NAME}${COREOS_KERNEL_EXT}"
COREOS_KERNEL0 ??= "${DEPLOY_DIR_IMAGE}/${COREOS_KERNEL0_FILENAME}"
COREOS_KERNEL1_FILENAME ??= "${COREOS_KERNEL1_NAME}${COREOS_KERNEL_EXT}"
COREOS_KERNEL1 ??= "${DEPLOY_DIR_IMAGE}/${COREOS_KERNEL1_FILENAME}"

# Kernel command line
# ==============================================================================

APPEND += "rootwait "
COREOS_ROOTFS0_ROOT ??= "PARTLABEL=rootfs0"
COREOS_ROOTFS1_ROOT ??= "PARTLABEL=rootfs1"
COREOS_KERNEL0_CMDLINE ??= "root=${COREOS_ROOTFS0_ROOT} ${APPEND}"
COREOS_KERNEL1_CMDLINE ??= "root=${COREOS_ROOTFS1_ROOT} ${APPEND}"

COREOS_UKI_PART_KERNEL_FILENAME ??= "${KERNEL_IMAGETYPE}-${MACHINE}${KERNEL_IMAGE_BIN_EXT}"
COREOS_UKI_PART_KERNEL ??= "${DEPLOY_DIR_IMAGE}/${COREOS_UKI_PART_KERNEL_FILENAME}"
COREOS_UKI_PART_STUB_FILENAME ??= "kernel-stub${EFI_ARCH}.efi"
COREOS_UKI_PART_STUB ??= "${STAGING_LIBDIR}/efibootguard/${COREOS_UKI_PART_STUB_FILENAME}"


# UKI Generation
# ==============================================================================

do_bundle_uki() {
    deployDir="${DEPLOY_DIR_IMAGE}"

    # Create an array with device tree if any
    DTB_PARAMS=""
    for dtb in ${KERNEL_DEVICETREE}; do
        # Bitbake allow full path inside KERNEL_DEVICETREE, but we want the
        # filename only
        dtb=$(basename "${dtb}")
        DTB_PARAMS="${DTB_PARAMS} --dtb=${deployDir}/${dtb}"
    done

    echo "kernel: ${COREOS_UKI_PART_KERNEL_FILENAME}"
    echo "dtb: ${DTB_PARAMS}"
    echo "cmdline0: ${COREOS_KERNEL0_CMDLINE}"
    echo "cmdline1: ${COREOS_KERNEL1_CMDLINE}"

    bg_gen_unified_kernel \
        "${COREOS_UKI_PART_STUB}" \
        "${COREOS_UKI_PART_KERNEL}" \
        "${COREOS_KERNEL0}" \
        --cmdline "${COREOS_KERNEL0_CMDLINE}" \
        ${DTB_PARAMS}

     bg_gen_unified_kernel \
        "${COREOS_UKI_PART_STUB}" \
        "${COREOS_UKI_PART_KERNEL}" \
        "${COREOS_KERNEL1}" \
        --cmdline "${COREOS_KERNEL1_CMDLINE}" \
        ${DTB_PARAMS}

    coreos_efi_secureboot_sign_app "${deployDir}/${COREOS_KERNEL0_FILENAME}"
    coreos_efi_secureboot_sign_app "${deployDir}/${COREOS_KERNEL1_FILENAME}"
}

do_bundle_uki[depends] += "virtual/kernel:do_deploy efibootguard-native:do_populate_sysroot efibootguard:do_populate_sysroot"
addtask bundle_uki after do_rootfs before do_image
