# SPDX-License-Identifier: GPL-3.0-or-later
"""
Worker class to build AMD64 images.
"""

from .. import library
from .efi import EFIImageBuilder


class AMD64ImageBuilder(EFIImageBuilder):
    """Image builder for all amd64 targets."""
    architecture = 'amd64'
    kernel_flavor = 'amd64'
    efi_architecture = 'x64'
    grub_target = 'x86_64-efi'
    secure_boot = True
    include_non_free_firmware = True

    def __init__(self, *args, **kwargs):
        """Initialize builder object."""
        super().__init__(*args, **kwargs)
        self.packages += [
            'grub-efi-amd64-signed',
            'grub-efi-amd64',
            'shim-signed',
            # Firmware packages list most from:
            # https://salsa.debian.org/live-team/live-tasks-non-free-firmware/
            'amd64-microcode',
            'bluez-firmware',
            'firmware-amd-graphics',
            'firmware-atheros',
            'firmware-brcm80211',
            'firmware-intel-graphics',
            'firmware-intel-misc',
            'firmware-intel-sound',
            # 'firmware-ipw2x00', # Requires agreeing to license
            'firmware-iwlwifi',
            'firmware-libertas',
            'firmware-linux',
            'firmware-linux-free',
            'firmware-linux-nonfree',
            'firmware-mediatek',
            'firmware-nvidia-graphics',
            'firmware-realtek',
            'firmware-sof-signed',
            'intel-microcode',
        ]

    @classmethod
    def get_target_name(cls):
        """Return the name of the target for an image builder."""
        return 'amd64'

    @classmethod
    def install_boot_loader(cls, state):
        """Install the DTB files and boot manager."""
        super().install_boot_loader(state)

        # In typical UEFI systems, EFI boot manager is available and all the OS
        # list themselves as boot manager configuration in NVRAM. In many SBCs,
        # NVRAM may not be present. In our case, since we distribute disk
        # images, we don't have other operating system to boot. So, install
        # grub as the boot manager.
        library.run_in_chroot(state, ['mkdir', '-p', '/boot/efi/EFI/boot/'])
        library.run_in_chroot(state, [
            'cp', f'/boot/efi/EFI/debian/shim{cls.efi_architecture}.efi',
            f'/boot/efi/EFI/boot/boot{cls.efi_architecture}.efi'
        ])
        library.run_in_chroot(state, [
            'cp', f'/boot/efi/EFI/debian/fb{cls.efi_architecture}.efi',
            f'/boot/efi/EFI/boot/fb{cls.efi_architecture}.efi'
        ])
        library.run_in_chroot(state, [
            'cp', f'/boot/efi/EFI/debian/mm{cls.efi_architecture}.efi',
            f'/boot/efi/EFI/boot/mm{cls.efi_architecture}.efi'
        ])
