# SPDX-License-Identifier: GPL-3.0-or-later
"""
Worker class to build Raspberry Pi 64-bit image.
"""

from .. import library
from ..builder import ImageBuilder


class RaspberryPi64ImageBuilder(ImageBuilder):
    """Image builder for Raspberry Pi 64-bit target."""
    architecture = 'arm64'
    boot_loader = None
    firmware_filesystem_type = 'vfat'
    firmware_size = '256MiB'
    include_non_free_firmware = True
    kernel_flavor = 'arm64'
    machine = 'raspberry64'
    update_initramfs = False

    def __init__(self, arguments):
        """Add to list of packages."""
        super().__init__(arguments)
        self.packages += ['firmware-brcm80211']

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

    def install_boot_loader(self, state):
        """Install the firmware onto the image."""
        uuid = library.get_uuid_of_device(state['devices']['root'])
        script = '''
set -e
set -x
set -o pipefail

# This will trigger installing firmware and updating initramfs.
apt-get install raspi-firmware

# Fixup cmdline.txt and set defaults
echo "console=tty0 console=ttyS1,115200 root=UUID={uuid} rw fsck.repair=yes net.ifnames=0 rootwait" >/boot/firmware/cmdline.txt
sed -i 's/^#ROOTPART=.*/ROOTPART=UUID={uuid}/' /etc/default/raspi-firmware
'''.format(uuid=uuid)
        library.run_in_chroot(state, ['bash', '-c', script])
