#!/usr/bin/env python3

# Copyright: 2026 Hector CAO <hector.cao@canonical.com>
# SPDX-License-Identifier: GPL-3.0-or-later

# Test: verify consumer packages pull in only the base virt variants, not -hwe.
#
# Removes any installed -hwe virt packages, then installs a set of external
# packages that depend on libvirt/qemu (debvm, genimage, sbuild-qemu). It then
# asserts that no -hwe package got pulled in and that at least one base virt
# package is present.

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import hwe_lib
from hwe_lib import (
    exit_with_failure,
    log_installed_virt_packages,
    remove_all_hwe_virt_packages,
    run_cmd,
    run_cmd_allow_fail,
    verify_only_variant,
)

# Default consumer packages to install, with any per-package extra apt args.
CONSUMER_PACKAGES = ("debvm", "genimage", "sbuild-qemu")
CONSUMER_PACKAGE_ARGS = {"genimage": ["--install-suggests"]}


def main():
    hwe_lib.LOG_FILE = os.environ.get("LOG_FILE", "check-default.log")
    os.environ["DEBIAN_FRONTEND"] = "noninteractive"

    open(hwe_lib.LOG_FILE, "w").close()

    if not run_cmd(
        "Refreshing apt metadata",
        "apt-get", "-o", "APT::Sandbox::User=root", "-y", "update",
    ):
        exit_with_failure("failed to refresh apt metadata", "after apt update")

    run_cmd_allow_fail(
        "Removing external packages (best-effort)",
        "apt-get", "remove", "-y", *CONSUMER_PACKAGES,
    )

    remove_all_hwe_virt_packages()
    log_installed_virt_packages("after removing all HWE virt packages")

    for pkg in CONSUMER_PACKAGES:
        extra_args = CONSUMER_PACKAGE_ARGS.get(pkg, [])
        run_cmd_allow_fail(
            f"Installing {pkg}",
            "apt-get", "install", "-y", *extra_args,
            "-o", "Dpkg::Options::=--force-confnew", pkg,
        )

    log_installed_virt_packages("after consumer apps installationn")

    if not verify_only_variant("base"):
        exit_with_failure(
            "base variant verification failed",
            "after final base variant verification",
        )

    print(f"Detailed command output saved to: {hwe_lib.LOG_FILE}")
    print("Validation passed. Only base qemu variants are installed.")


if __name__ == "__main__":
    hwe_lib.run_main(main)
