#!/usr/bin/env python3

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

# Test: verify switching between the base and -hwe libvirt daemon packages.
#
# Installs libvirt-daemon-system, confirms libvirtd responds and is active,
# then installs libvirt-daemon-system-hwe (the HWE variant) and confirms
# libvirtd still works. Finally checks that the libvirtd service remains
# enabled and active.

import os
import sys

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

from tenacity import (
    retry,
    stop_after_attempt,
    wait_exponential,
)

import hwe_lib
from hwe_lib import exit_with_failure, run_cmd, step, systemd_check


@retry(
    stop=stop_after_attempt(6),
    wait=wait_exponential(multiplier=1, max=30),
)
def check_libvirtd_works(context):
    virsh_ok = run_cmd(
        f"virsh list --all ({context})", "virsh", "list", "--all"
    )
    if not (virsh_ok and systemd_check("is-active", "--quiet", "libvirtd")):
        step(f"libvirtd not ready yet ({context}); retrying")
        raise RuntimeError("libvirtd not active")

def install_and_check(context):
    package = "libvirt-daemon-system-hwe"
    if context == "base":
        package = "libvirt-daemon-system"

    if not run_cmd(
        f"Installing {package}",
        "apt-get", "install", "-y",
        "-o", "Dpkg::Options::=--force-confnew", package,
    ):
        exit_with_failure(
            f"failed to install {package}",
            f"after {package} install",
        )
    check_libvirtd_works(f"after installing {package}")

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

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

    # apt update
    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")

    # install base libvirt-daemon-system and check that libvirtd works
    install_and_check("base")

    # install HWE libvirt-daemon-system and check that libvirtd works
    install_and_check("hwe")

    # install base libvirt-daemon-system back and check that libvirtd works
    install_and_check("base")

    print(f"Detailed command output saved to: {hwe_lib.LOG_FILE}")
    print(
        "Validation passed. libvirtd works with both base and -hwe daemon packages."
    )


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