import logging
import re

from test_automation_suite.utility.cmd import run_cmd_t

logger = logging.getLogger(__name__)


def fix_boot_order() -> None:
    logger.info("removing iPXE.efi to prevent it booting into webfai")
    _res, _err = run_cmd_t("rm -f /boot/efi/EFI/BOOT/iPXE.efi")
    # Ensure the operating system is the first boot option, since some systems respect
    # the configured boot order.
    boot_order, _err = run_cmd_t("efibootmgr")
    os_boot_num = ""
    match = re.search(
        "^Boot([(0-9)]{4})(.)*(TUXEDO|ubuntu|TUXEDO OS)",
        boot_order,
        flags=re.MULTILINE | re.IGNORECASE,
    )
    if match:
        os_boot_num = match.group(1)
    if os_boot_num:
        logger.info("putting Tuxedo OS as first option")
        _run, _err = run_cmd_t("efibootmgr -o " + os_boot_num)


def fix_boot_order_os() -> None:
    logger.info("trying to set boot order to boot autotest stick first")
    boot_order, err = run_cmd_t("efibootmgr")
    if err:
        logger.error("could not run efibootmgr, boot order not modified!")
    # webfai_boot_num = ""
    # match = re.search(
    #     "^Boot([(0-9)]{4})(.)*(iPXE|WebFAI|UEFI OS)",
    #     boot_order,
    #     flags=re.MULTILINE | re.IGNORECASE,
    # )
    # if match:
    #     webfai_boot_num = match.group(1)
    usb_boot_num = ""
    match = re.search(
        "^Boot([(0-9)]{4})(.)*(USB|General UDisk)",
        boot_order,
        flags=re.MULTILINE | re.IGNORECASE,
    )
    if match:
        usb_boot_num = match.group(1)
    if usb_boot_num:
        logger.info("putting usb stick as first option")
        # run, err = run_cmd_t(
        #     "efibootmgr -b " + usb_boot_num + " -a",
        # )  # enable auto boot stick
        _run, err = run_cmd_t(
            "efibootmgr -o " + usb_boot_num,
        )  # put usb stick as first boot option
        delete_all_bootnums_but_mine(boot_order, usb_boot_num)


def get_all_bootnums(bootmgr_output: str) -> list[str]:
    return re.findall(
        "^Boot([(0-9)]{4})",
        bootmgr_output,
        flags=re.MULTILINE | re.IGNORECASE,
    )


def delete_all_bootnums_but_mine(bootmgr_output: str, my_num: str) -> None:
    all_nums = get_all_bootnums(bootmgr_output)
    if my_num in all_nums:
        all_nums.remove(my_num)
    for num in all_nums:
        _run, _err = run_cmd_t("efibootmgr -b " + num + " -B")


def delete_efi_partition() -> None:
    res, _err = run_cmd_t("rm -rf /boot/efi/")
    res, _err = run_cmd_t('mount | grep "/boot/efi"')
    partition = res.split(" ")[0].strip()
    res, _err = run_cmd_t("mkfs " + partition)
