#!/usr/bin/env python3

import os
import subprocess
import tarfile

import common
from shell_helpers import LF

class DockerComponent(self.Component):
    def get_argparse_args(self):
        return {
            'description': '''\
Build a guest root filesystem based on prebuilt Docker Ubuntu root filesystems.

See also: https://github.com/cirosantilli/linux-kernel-module-cheatTODO#ubuntu-guest-setup
'''
        }

    def build(self):
        build_dir = self.get_build_dir()
        container_name = 'lkmc-guest'
        target_dir = os.path.join('/root', 'linux-kernel-module-cheat')
        os.makedirs(build_dir, exist_ok=True)
        containers = self.sh.check_output([
                'docker',
                'ps',
                '-a',
                '--format', '{{.Names}}',
        ]).decode()
        if container_name in containers.split():
            self.sh.run_cmd([
                'docker',
                'rm',
                container_name,
            ])
        self.sh.run_cmd([
            'docker',
            'create',
            '--name', container_name,
            '--net',
            'host',
            '-i',
            '--privileged',
            '-t',
            '-w', target_dir,
            '-v', '{}:{}'.format(kwargs['root_dir'], target_dir),
            'ubuntu:20.04',
            'bash',
        ])
        self.sh.run_cmd([
            'docker',
            'export',
            '-o',
            kwargs['docker_tar_file'],
            container_name,
        ])
        tar = tarfile.open(kwargs['docker_tar_file'])
        tar.extractall(kwargs['docker_tar_dir'])
        tar.close()
        # sudo not required in theory
        # https://askubuntu.com/questions/1046828/how-to-run-libguestfs-tools-tools-such-as-virt-make-fs-without-sudo
        self.sh.run_cmd([
            'virt-make-fs',
            '--format', 'raw',
            '--size', '+1G',
            '--type', 'ext2',
            kwargs['docker_tar_dir'],
            kwargs['docker_rootfs_raw_file'],
        ])
        self.raw_to_qcow2(prebuilt=True)

    def get_build_dir(self):
        return kwargs['docker_build_dir']

    def get_default_args(self):
        return {'docker': True}

Main().cli()
