<reponame>KunYi/meta-srg52x
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# DESCRIPTION
# This implements the 'bootpart' source plugin class for 'wic'
#
# AUTHORS
# KunYi <<EMAIL>>
#

import logging
import os
import glob

from wic import WicError
from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
from wic.plugins.source.rootfs import RootfsPlugin
from wic.misc import (exec_cmd, exec_native_cmd,
                            get_bitbake_var, BOOTDD_EXTRA_SPACE)
from wic import WicError

logger = logging.getLogger('wic')

class BootPartitionPlugin(SourcePlugin):
    """
    Create boot partition.
    """
    name = 'bootpart'

    @classmethod 
    def gen_ubootscript(cls, part, source_params, cr, rootdir, hdddir):
        u_boot_script = os.path.join(rootdir,
                                     "etc/default/u-boot-script")
        if not os.path.exists(u_boot_script):
            raise WicError("u-boot-scripts package not installed")

        # Write new /etc/default/u-boot-script
        '''
        with open(u_boot_script, 'w') as cfg:
            cfg.write('# Generated by wic, bootpart plugin\n')
            cfg.write('ROOT_PARTITION="%d"\n' % part.realnum)
            cfg.write('KERNEL_ARGS="root=%s %s"\n' % \
                (cr.rootdev, cr.ks.bootloader.append or ""))
            no_initrd = source_params.get('no_initrd') or ''
            cfg.write('NO_INITRD="%s"\n' % no_initrd)
            overlays = source_params.get('overlays') or ''
            cfg.write('OVERLAYS="%s"\n' % overlays)
            script_prepend = source_params.get('script_prepend') or ''
            cfg.write('SCRIPT_PREPEND="%s"\n' % script_prepend)
        '''
        # Run update-u-boot-script in the target rootfs
        results = glob.glob(os.path.join("/usr/bin/qemu-*-static"))
        qemu_static = results[0] if len(results) > 0 else None
        if qemu_static:
            cp_cmd = "cp -L %s %s/usr/bin" % (qemu_static, rootdir)
            exec_cmd(cp_cmd)
        update_cmd = "chroot %s sh -c update-u-boot-script" % rootdir
        exec_cmd(update_cmd)
        if qemu_static:
            rm_cmd = "rm -f %s/usr/bin/%s" % (rootdir, qemu_static)
            exec_cmd(rm_cmd)

    """
    Called before do_prepare_partition()
    """
    @classmethod
    def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
                             oe_builddir, bootimg_dir, kernel_dir,
                             rootfs_dir, native_sysroot):
        """
        Called to do the actual content population for a partition i.e. it
        'prepares' the partition to be incorporated into the image.
        In this case, prepare content for boot partition.
        """

        hdddir = "%s/hdd/boot" % cr_workdir
        install_cmd = "install -d %s" % hdddir
        exec_cmd(install_cmd)

        # ROOTFS_DIR same
        # image_rootfs: /work/build/tmp/work/srg52-buster-armhf/srg52-image-srg-3352c-wic-targz-img/1.0-r0/rootfs
        image_rootfs = get_bitbake_var("IMAGE_ROOTFS")

        kernel_file = "vmlinuz"
        kernel = os.path.basename(os.path.realpath(os.path.join(image_rootfs, kernel_file)))
        staging_kernel_dir = "%s/boot" % image_rootfs

        kernel_version = kernel.strip(kernel_file + '-')

        cls.gen_ubootscript(part, source_params, creator, image_rootfs, hdddir)

        initrd = "initrd.img-%s" % (kernel_version)
        config = "config-%s" % (kernel_version)
        mapfile = "System.map-%s" % (kernel_version)
        bootscript = "boot.scr"

        cmds = ("install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, kernel, hdddir, kernel),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, initrd, hdddir, initrd),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, config, hdddir, config),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, mapfile, hdddir, mapfile),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, bootscript, hdddir, bootscript))

        for install_cmd in cmds:
            exec_cmd(install_cmd)

        dtbs_path = "%s/usr/lib/linux-image-%s" % (image_rootfs, kernel_version)

        dtbsdir = "%s/dtbs" % hdddir
        overlaydir = "%s/overlay" % dtbsdir

        cmds = (("install -d %s" % dtbsdir),
            ("install -d %s" % overlaydir))

        for install_cmd in cmds:
            exec_cmd(install_cmd)

        # logger.info("dtbs_path:%s", dtbs_path)        
        for root, dir, files in os.walk(dtbs_path):
            for f in files:
                if len(dir) > 0:
                    install_cmd = "install -m 0644 %s/%s %s/%s" % (root, f, dtbsdir, f)
                else:
                    install_cmd = "install -m 0644 %s/%s %s/%s" % (root, f, overlaydir, f)

                # logger.info("dir:%s, f:%s", dir, f)
                # logger.info("dtb:%s", install_cmd)
                exec_cmd(install_cmd)

        du_cmd = "du -bks %s" % hdddir
        out = exec_cmd(du_cmd)
        blocks = int(out.split()[0])

        extra_blocks = part.get_extra_block_count(blocks)

        if extra_blocks < BOOTDD_EXTRA_SPACE:
            extra_blocks = BOOTDD_EXTRA_SPACE

        blocks += extra_blocks

        logger.debug("Added %d extra blocks to %s to get to %d total blocks",
                     extra_blocks, part.mountpoint, blocks)

        bootimg = "%s/boot.img" % cr_workdir
        genimg_cmd = "dd if=/dev/zero of=%s bs=512 count=%d" % (bootimg, blocks)
        exec_native_cmd(genimg_cmd, native_sysroot)

        extraopts = "-F -i 8192"
        fstype = "ext4"
        mkfs_cmd = "mkfs.%s %s %s -L boot -d %s" % \
            (fstype, extraopts, bootimg, hdddir)
        exec_native_cmd(mkfs_cmd, native_sysroot)

        mkfs_cmd = "fsck.%s -pvfD %s" % (fstype, bootimg)
        exec_native_cmd(mkfs_cmd, native_sysroot)

        du_cmd = "du -Lbks %s" % bootimg
        out = exec_cmd(du_cmd)
        bootimg_size = out.split()[0]

        part.size = int(bootimg_size)
        part.source_file = bootimg


# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# DESCRIPTION
# This implements the 'bootpart' source plugin class for 'wic'
#
# AUTHORS
# KunYi <<EMAIL>>
#

import logging
import os
import glob

from wic import WicError
from wic.engine import get_custom_config
from wic.pluginbase import SourcePlugin
from wic.plugins.source.rootfs import RootfsPlugin
from wic.misc import (exec_cmd, exec_native_cmd,
                            get_bitbake_var, BOOTDD_EXTRA_SPACE)
from wic import WicError

logger = logging.getLogger('wic')

class BootPartitionPlugin(SourcePlugin):
    """
    Create boot partition.
    """
    name = 'bootpart'

    @classmethod 
    def gen_ubootscript(cls, part, source_params, cr, rootdir, hdddir):
        u_boot_script = os.path.join(rootdir,
                                     "etc/default/u-boot-script")
        if not os.path.exists(u_boot_script):
            raise WicError("u-boot-scripts package not installed")

        # Write new /etc/default/u-boot-script
        '''
        with open(u_boot_script, 'w') as cfg:
            cfg.write('# Generated by wic, bootpart plugin\n')
            cfg.write('ROOT_PARTITION="%d"\n' % part.realnum)
            cfg.write('KERNEL_ARGS="root=%s %s"\n' % \
                (cr.rootdev, cr.ks.bootloader.append or ""))
            no_initrd = source_params.get('no_initrd') or ''
            cfg.write('NO_INITRD="%s"\n' % no_initrd)
            overlays = source_params.get('overlays') or ''
            cfg.write('OVERLAYS="%s"\n' % overlays)
            script_prepend = source_params.get('script_prepend') or ''
            cfg.write('SCRIPT_PREPEND="%s"\n' % script_prepend)
        '''
        # Run update-u-boot-script in the target rootfs
        results = glob.glob(os.path.join("/usr/bin/qemu-*-static"))
        qemu_static = results[0] if len(results) > 0 else None
        if qemu_static:
            cp_cmd = "cp -L %s %s/usr/bin" % (qemu_static, rootdir)
            exec_cmd(cp_cmd)
        update_cmd = "chroot %s sh -c update-u-boot-script" % rootdir
        exec_cmd(update_cmd)
        if qemu_static:
            rm_cmd = "rm -f %s/usr/bin/%s" % (rootdir, qemu_static)
            exec_cmd(rm_cmd)

    """
    Called before do_prepare_partition()
    """
    @classmethod
    def do_prepare_partition(cls, part, source_params, creator, cr_workdir,
                             oe_builddir, bootimg_dir, kernel_dir,
                             rootfs_dir, native_sysroot):
        """
        Called to do the actual content population for a partition i.e. it
        'prepares' the partition to be incorporated into the image.
        In this case, prepare content for boot partition.
        """

        hdddir = "%s/hdd/boot" % cr_workdir
        install_cmd = "install -d %s" % hdddir
        exec_cmd(install_cmd)

        # ROOTFS_DIR same
        # image_rootfs: /work/build/tmp/work/srg52-buster-armhf/srg52-image-srg-3352c-wic-targz-img/1.0-r0/rootfs
        image_rootfs = get_bitbake_var("IMAGE_ROOTFS")

        kernel_file = "vmlinuz"
        kernel = os.path.basename(os.path.realpath(os.path.join(image_rootfs, kernel_file)))
        staging_kernel_dir = "%s/boot" % image_rootfs

        kernel_version = kernel.strip(kernel_file + '-')

        cls.gen_ubootscript(part, source_params, creator, image_rootfs, hdddir)

        initrd = "initrd.img-%s" % (kernel_version)
        config = "config-%s" % (kernel_version)
        mapfile = "System.map-%s" % (kernel_version)
        bootscript = "boot.scr"

        cmds = ("install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, kernel, hdddir, kernel),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, initrd, hdddir, initrd),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, config, hdddir, config),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, mapfile, hdddir, mapfile),
                "install -m 0644 %s/%s %s/%s" %
                (staging_kernel_dir, bootscript, hdddir, bootscript))

        for install_cmd in cmds:
            exec_cmd(install_cmd)

        dtbs_path = "%s/usr/lib/linux-image-%s" % (image_rootfs, kernel_version)

        dtbsdir = "%s/dtbs" % hdddir
        overlaydir = "%s/overlay" % dtbsdir

        cmds = (("install -d %s" % dtbsdir),
            ("install -d %s" % overlaydir))

        for install_cmd in cmds:
            exec_cmd(install_cmd)

        # logger.info("dtbs_path:%s", dtbs_path)        
        for root, dir, files in os.walk(dtbs_path):
            for f in files:
                if len(dir) > 0:
                    install_cmd = "install -m 0644 %s/%s %s/%s" % (root, f, dtbsdir, f)
                else:
                    install_cmd = "install -m 0644 %s/%s %s/%s" % (root, f, overlaydir, f)

                # logger.info("dir:%s, f:%s", dir, f)
                # logger.info("dtb:%s", install_cmd)
                exec_cmd(install_cmd)

        du_cmd = "du -bks %s" % hdddir
        out = exec_cmd(du_cmd)
        blocks = int(out.split()[0])

        extra_blocks = part.get_extra_block_count(blocks)

        if extra_blocks < BOOTDD_EXTRA_SPACE:
            extra_blocks = BOOTDD_EXTRA_SPACE

        blocks += extra_blocks

        logger.debug("Added %d extra blocks to %s to get to %d total blocks",
                     extra_blocks, part.mountpoint, blocks)

        bootimg = "%s/boot.img" % cr_workdir
        genimg_cmd = "dd if=/dev/zero of=%s bs=512 count=%d" % (bootimg, blocks)
        exec_native_cmd(genimg_cmd, native_sysroot)

        extraopts = "-F -i 8192"
        fstype = "ext4"
        mkfs_cmd = "mkfs.%s %s %s -L boot -d %s" % \
            (fstype, extraopts, bootimg, hdddir)
        exec_native_cmd(mkfs_cmd, native_sysroot)

        mkfs_cmd = "fsck.%s -pvfD %s" % (fstype, bootimg)
        exec_native_cmd(mkfs_cmd, native_sysroot)

        du_cmd = "du -Lbks %s" % bootimg
        out = exec_cmd(du_cmd)
        bootimg_size = out.split()[0]

        part.size = int(bootimg_size)
        part.source_file = bootimg
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # DESCRIPTION # This implements the 'bootpart' source plugin class for 'wic' # # AUTHORS # KunYi <<EMAIL>> # Create boot partition. # Write new /etc/default/u-boot-script with open(u_boot_script, 'w') as cfg:             cfg.write('# Generated by wic, bootpart plugin\n')             cfg.write('ROOT_PARTITION="%d"\n' % part.realnum)             cfg.write('KERNEL_ARGS="root=%s %s"\n' % \                 (cr.rootdev, cr.ks.bootloader.append or ""))             no_initrd = source_params.get('no_initrd') or ''             cfg.write('NO_INITRD="%s"\n' % no_initrd)             overlays = source_params.get('overlays') or ''             cfg.write('OVERLAYS="%s"\n' % overlays)             script_prepend = source_params.get('script_prepend') or ''             cfg.write('SCRIPT_PREPEND="%s"\n' % script_prepend) # Run update-u-boot-script in the target rootfs Called before do_prepare_partition() Called to do the actual content population for a partition i.e. it         'prepares' the partition to be incorporated into the image.         In this case, prepare content for boot partition. # ROOTFS_DIR same # image_rootfs: /work/build/tmp/work/srg52-buster-armhf/srg52-image-srg-3352c-wic-targz-img/1.0-r0/rootfs # logger.info("dtbs_path:%s", dtbs_path) # logger.info("dir:%s, f:%s", dir, f) # logger.info("dtb:%s", install_cmd)