# (c) 2011-2020 Michał Górny <mgorny@gentoo.org>
# SPDX-License-Identifier: GPL-2.0-or-later

import logging
import os
import subprocess
import typing

from ecleankernel.bootloader.grub import GRUB


grub2_autogen_header = '''#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by '''


class GRUB2(GRUB):
    name = 'grub2'
    kernel_re = r'^\s*linux\s*(\([^)]+\))?(?P<path>\S+)'
    def_path = (os.environ.get("GRUB_CFG"),
                '/boot/grub/grub.cfg',
                '/boot/grub2/grub.cfg',
                )

    def __init__(self) -> None:
        super().__init__()
        self._autogen = self._content.startswith(grub2_autogen_header)

    def _get_kernels(self,
                     content: str
                     ) -> typing.Iterable[str]:
        if self._autogen:
            logging.debug('Config is autogenerated, ignoring')
            return ()
        return GRUB._get_kernels(self, content)

    def has_postrm(self) -> bool:
        return self._autogen

    def postrm(self) -> None:
        if self._autogen:
            logging.debug('Calling grub2-mkconfig')
            try:
                subprocess.call(['grub-mkconfig', '-o', self.path])
                return
            except FileNotFoundError:
                pass
            subprocess.call(['grub2-mkconfig', '-o', self.path])
