#!/usr/bin/env python3

# SPDX-License-Identifier: GPL-3.0-or-later

# Test: verify virtlogd survives purging the base libvirt-daemon-log package.
#
# Since purging action can remove dynamic conffiles of a package and since
# hwe and base package share the same dynamic conffiles, purging a package
# while the counterpart package is installed can remove the dynamic conffiles
# which can break the counterpart package.
#
# Installs libvirt-daemon-log and confirms virtlogd is up, then installs
# libvirt-daemon-log-hwe (the HWE variant) and confirms virtlogd is still up.
# Finally purges the base libvirt-daemon-log and confirms virtlogd remains up
# and enabled (provided by the -hwe package).

import os
import subprocess
import sys

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

import hwe_lib
from hwe_lib import (
    exit_with_failure,
    find_matching_entries,
    run_cmd,
    step,
    systemd_check,
)


# Verify virtlogd is up. It is socket-activated, so accept either the service
# or its activation socket being active.
def check_virtlogd_works(context):
    step(f"Verifying virtlogd is running ({context})")
    if not systemd_check("is-active", "--quiet", "virtlogd") and not systemd_check(
        "is-active", "--quiet", "virtlogd.socket"
    ):
        exit_with_failure("virtlogd is not running", context)

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

    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_virtlogd_works(f"after installing {package}")

def purge(context):
    package = "libvirt-daemon-log-hwe"
    if context == "base":
        package = "libvirt-daemon-log"

    if not run_cmd(
        f"Purging {package}", "apt-get", "purge", "-y", package
    ):
        exit_with_failure(
            f"failed to purge {package}",
            f"after purging {package}"
        )

def main():
    hwe_lib.LOG_FILE = os.environ.get("LOG_FILE", "check-purge.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-log
    install_and_check("base")

    # install HWE libvirt-daemon-log
    install_and_check("hwe")

    # purge base libvirt-daemon-log
    purge("base")

    step("Verifying virtlogd is running and enabled")
    check_virtlogd_works("after purging libvirt-daemon-log")
    if not systemd_check("is-enabled", "--quiet", "virtlogd") and not systemd_check(
        "is-enabled", "--quiet", "virtlogd.socket"
    ):
        exit_with_failure("virtlogd is not enabled", "final service state check")

    # restart virtlogd and check still running
    run_cmd("Restarting virtlogd", "systemctl", "restart", "virtlogd")
    check_virtlogd_works("after restarting virtlogd")

    # purge HWE libvirt-daemon-log
    purge("hwe")

    # check purging has been done properly
    run_cmd("Reloading systemd manager configuration", "systemctl", "daemon-reload")

    step("Verifying virtlogd systemd unit is removed")
    unit_files = subprocess.run(
        ["systemctl", "list-unit-files", "virtlogd*", "--no-legend"],
        capture_output=True,
        text=True,
        check=False,
    )
    if any(line.strip() for line in unit_files.stdout.splitlines()):
        exit_with_failure(
            "virtlogd systemd unit still present",
            "after purging libvirt-daemon-log-hwe",
        )

    step("Verifying virtlogd /etc/systemd links are removed")
    if find_matching_entries("/etc/systemd", "virtlogd*"):
        exit_with_failure(
            "virtlogd /etc/systemd link still present",
            "after purging libvirt-daemon-log-hwe",
        )

    print(f"Detailed command output saved to: {hwe_lib.LOG_FILE}")
    print(
        "Validation passed. virtlogd survives purging the base "
        "libvirt-daemon-log package."
    )


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