#!/usr/bin/env python3
"""Create and configure a small two-node Kubernetes cluster on libvirt.

This is intentionally a single-file installer with no Python dependencies.
It installs missing host-side libvirt/KVM/SSH utilities using apt, dnf, yum,
or pacman, then downloads the configured cloud image when it is not already
available. The VM and Kubernetes
settings mirror 123cluster-docs/k8s-cluster-creation.md, reduced to one
control-plane node and one worker.

Example:
    sudo python3 k8s_script/install_k8s_cluster.py

The script is safe to re-run for the same VM names: existing VMs and an
already-initialized cluster are left in place, while missing configuration is
completed where possible.
"""

from __future__ import annotations

import argparse
from contextlib import contextmanager
import grp
import json
import os
import pwd
from pathlib import Path
import re
import shlex
import subprocess
import sys
import tempfile
import threading
import time
import traceback
from datetime import datetime, timezone
from urllib.parse import urlparse
from urllib.request import Request, urlopen
from dataclasses import dataclass


NETWORK_NAME = "k8s"
BRIDGE_NAME = "virbr1"
SUBNET = "192.168.123.0/24"
NETMASK = "255.255.255.0"
GATEWAY = "192.168.123.1"
CONTROL_IP = "192.168.123.100"
WORKER_IP = "192.168.123.101"
CONTROL_MAC = "52:54:00:12:34:00"
WORKER_MAC = "52:54:00:12:34:01"
CONTROL_PLANE_ENDPOINT = f"{CONTROL_IP}:6443"
# Small defaults for nested/local testing. Increase these independently for
# production deployments; values are MiB because virt-install expects MiB.
CONTROL_PLANE_MEMORY_MIB = 8192
WORKER_MEMORY_MIB = 16384
DHCP_START = "192.168.123.150"
DHCP_END = "192.168.123.199"
METALLB_START = "192.168.123.200"
METALLB_END = "192.168.123.249"
POD_CIDR = "172.16.0.0/16"
DNS_SERVERS = "1.1.1.1, 8.8.8.8"
LIBVIRT_URI = "qemu:///system"
KUBEADM_KUBECONFIG = "/etc/kubernetes/admin.conf"
# Software-emulated nested VMs can take several minutes to pull and start
# Calico images. Increase this independently for particularly slow hosts.
CALICO_ROLLOUT_TIMEOUT_SECONDS = 1800
# The Calico operator manifest contains many CRDs. API requests can be slow
# when the nested guests run without KVM acceleration.
KUBECTL_REQUEST_TIMEOUT_SECONDS = 300
CALICO_MANIFEST_APPLY_RETRIES = 5
METALLB_ROLLOUT_TIMEOUT_SECONDS = 1800
# containerd may still be loading the CRI plugin immediately after a restart,
# especially on a freshly initialized CentOS guest.
CONTAINERD_CRI_READY_TIMEOUT_SECONDS = 120
EXTERNAL_ACCESS_NAMESPACE = "kube-system"
EXTERNAL_ACCESS_SERVICE_ACCOUNT = "external-controller"
EXTERNAL_ACCESS_SECRET = "external-controller-token"

# Select these together when changing the VM guest distribution. The node
# setup script detects apt-get or dnf inside each guest at runtime.
# GUEST_OS_VARIANT = "ubuntu22.04"
GUEST_OS_VARIANT = "centos-stream9"
# Use "auto" to select sudo on Ubuntu and wheel on CentOS/RHEL-family guests.
GUEST_ADMIN_GROUP = "auto"
# Use "auto" to match en* on Ubuntu and eth* on CentOS/RHEL-family images.
GUEST_INTERFACE_MATCH = "auto"
# DEFAULT_BASE_IMAGE_URL = "https://cloud-images.ubuntu.com/minimal/releases/noble/release/ubuntu-24.04-minimal-cloudimg-amd64.img"
DEFAULT_BASE_IMAGE_URL = "https://cloud.centos.org/centos/9-stream/x86_64/images/CentOS-Stream-GenericCloud-9-latest.x86_64.qcow2"
# Detailed command output is appended to this file. Set an absolute path here
# or override it with --log-file when integrating the installer elsewhere.
LOG_FILE_NAME = "install_k8s_cluster.log"

_LOG_HANDLE = None
_LOG_PATH: Path | None = None
_SPINNER_CHARS = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")


@dataclass(frozen=True)
class Node:
    name: str
    ip: str
    role: str
    memory_mib: int
    vcpus: int = 4
    mac: str = ""


def configure_logging(path: Path) -> None:
    """Open the detailed log in append mode and never truncate an old log."""
    global _LOG_HANDLE, _LOG_PATH
    path.parent.mkdir(parents=True, exist_ok=True)
    _LOG_PATH = path
    _LOG_HANDLE = path.open("a", encoding="utf-8", buffering=1)
    log_detail("\n" + "=" * 80)
    log_detail(f"Installer started: {datetime.now(timezone.utc).isoformat()}")


def close_logging() -> None:
    global _LOG_HANDLE
    if _LOG_HANDLE is not None:
        log_detail(f"Installer finished: {datetime.now(timezone.utc).isoformat()}")
        _LOG_HANDLE.close()
        _LOG_HANDLE = None


def log_detail(message: str) -> None:
    """Write diagnostic text to the append-only log, never to normal stdout."""
    if _LOG_HANDLE is None:
        return
    if not message.endswith("\n"):
        message += "\n"
    _LOG_HANDLE.write(message)
    _LOG_HANDLE.flush()


@contextmanager
def progress_step(name: str):
    """Display a compact spinner/result while the details go to the log."""
    log_detail(f"STEP START: {name}")
    interactive = sys.stdout.isatty()
    stop = threading.Event()
    thread = None

    if interactive:
        def spin() -> None:
            index = 0
            while not stop.wait(0.1):
                sys.stdout.write(f"\r{_SPINNER_CHARS[index % len(_SPINNER_CHARS)]} {name}")
                sys.stdout.flush()
                index += 1

        sys.stdout.write(f"\r{_SPINNER_CHARS[0]} {name}")
        sys.stdout.flush()
        thread = threading.Thread(target=spin, daemon=True)
        thread.start()
    else:
        print(f"⏳ {name}")

    try:
        yield
    except BaseException:
        stop.set()
        if thread is not None:
            thread.join()
        print(f"\r✗ {name}")
        log_detail(f"STEP FAILED: {name}")
        raise
    else:
        stop.set()
        if thread is not None:
            thread.join()
        print(f"\r✓ {name}")
        log_detail(f"STEP COMPLETE: {name}")


def authenticate_sudo() -> None:
    """Prompt for sudo credentials before progress output starts."""
    if os.geteuid() == 0 or not shutil_which("sudo"):
        return
    log_detail("Refreshing sudo credentials before installer steps")
    # Inherit the terminal deliberately so sudo's password prompt is displayed
    # directly and cannot collide with the spinner or log stream.
    result = subprocess.run(["sudo", "-v"], check=False)
    if result.returncode != 0:
        raise RuntimeError("sudo authentication failed")


def run(command: list[str], *, input_text: str | None = None,
        capture: bool = False, check: bool = True) -> subprocess.CompletedProcess[str]:
    """Run a host command and send all command details/output to the log."""
    command_text = shlex.join(command)
    log_detail("+ " + command_text)
    output_stream = _LOG_HANDLE if _LOG_HANDLE is not None else subprocess.DEVNULL
    result = subprocess.run(
        command,
        input=input_text,
        text=True,
        stdout=subprocess.PIPE if capture else output_stream,
        stderr=subprocess.PIPE if capture else output_stream,
        check=False,
    )
    if capture:
        if result.stdout:
            log_detail(result.stdout.rstrip("\n"))
        if result.stderr:
            log_detail(result.stderr.rstrip("\n"))
    if check and result.returncode:
        raise RuntimeError(f"command failed ({result.returncode}): {command_text}")
    return result


def require_commands() -> None:
    required = ("virsh", "virt-install", "qemu-img", "ssh", "ssh-keygen", "rsync")
    missing = [name for name in required if not shutil_which(name)]
    if not any(shutil_which(name) for name in ("genisoimage", "mkisofs")):
        missing.append("genisoimage or mkisofs")
    if missing:
        raise RuntimeError("missing host command(s): " + ", ".join(missing))


def shutil_which(command: str) -> str | None:
    """Small stdlib-only equivalent of shutil.which for this script."""
    for directory in os.environ.get("PATH", "").split(os.pathsep):
        candidate = Path(directory) / command
        if candidate.is_file() and os.access(candidate, os.X_OK):
            return str(candidate)
    return None


def host_privilege_prefix() -> list[str]:
    """Return the prefix needed for local system-libvirt operations."""
    if os.geteuid() == 0:
        return []
    if shutil_which("sudo"):
        return ["sudo"]
    raise RuntimeError(
        "local libvirt operations require root or the sudo command; "
        "cannot access qemu:///system"
    )


def login_user() -> str:
    """Return the human user whose login session should own the VM setup."""
    if os.geteuid() == 0 and os.environ.get("SUDO_USER"):
        return os.environ["SUDO_USER"]
    return pwd.getpwuid(os.getuid()).pw_name


def effective_group_names() -> set[str]:
    group_ids = set(os.getgroups()) | {os.getgid()}
    names = set()
    for group_id in group_ids:
        try:
            names.add(grp.getgrgid(group_id).gr_name)
        except KeyError:
            pass
    return names


def account_group_names(user: str) -> set[str]:
    """Return groups assigned to a user according to the system NSS database."""
    result = subprocess.run(
        ["id", "-nG", user],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode == 0:
        return set(result.stdout.split())
    return set()


def account_has_group(user: str, group: str) -> bool:
    if group in account_group_names(user):
        return True
    # Fallback for unusual NSS configurations where `id` is unavailable or
    # does not return supplementary groups consistently.
    group_info = grp.getgrnam(group)
    user_info = pwd.getpwnam(user)
    return group in group_info.gr_mem or user_info.pw_gid == group_info.gr_gid


def set_key_owner(path: Path, user: str) -> None:
    if os.geteuid() != 0:
        return
    user_info = pwd.getpwnam(user)
    os.chown(path, user_info.pw_uid, user_info.pw_gid)


def ensure_ssh_keypair(args: argparse.Namespace) -> None:
    """Create or complete the user's default ED25519 key pair."""
    private_key = args.ssh_key
    public_key = args.ssh_public_key
    user = login_user()

    private_key.parent.mkdir(parents=True, exist_ok=True)
    private_key.parent.chmod(0o700)
    set_key_owner(private_key.parent, user)

    if not private_key.exists():
        if public_key.exists():
            raise RuntimeError(
                f"public key exists but private key is missing: {private_key}; "
                "remove the orphan public key or provide --ssh-key"
            )
        log_detail(f"Generating ED25519 SSH key pair: {private_key}")
        run([
            "ssh-keygen", "-q", "-t", "ed25519",
            "-N", "", "-f", str(private_key), "-C", f"{user}@k8s-installer",
        ])
        set_key_owner(private_key, user)
        if private_key.with_name(private_key.name + ".pub").exists():
            set_key_owner(private_key.with_name(private_key.name + ".pub"), user)

    if not public_key.exists():
        log_detail(f"Deriving missing public key: {public_key}")
        result = run(["ssh-keygen", "-y", "-f", str(private_key)], capture=True)
        public_key.write_text(result.stdout.strip() + "\n", encoding="utf-8")
        public_key.chmod(0o644)
        set_key_owner(public_key, user)

    if not private_key.is_file() or not public_key.is_file():
        raise RuntimeError(
            f"SSH key pair is incomplete: {private_key} and {public_key}"
        )


def ensure_host_groups() -> bool:
    """Ensure libvirt/KVM groups are configured and active for this session.

    Returns False when the caller must start a new login session before the
    installer can continue. A root invocation can continue immediately, but
    still adds the groups to the original user when launched through sudo.
    """
    user = login_user()
    if user == "root":
        return True

    required_groups = []
    for group in ("libvirt", "kvm"):
        try:
            grp.getgrnam(group)
        except KeyError:
            log_detail(f"Host group {group!r} does not exist; continuing with sudo.")
        else:
            required_groups.append(group)

    if not required_groups:
        return True

    missing_account_groups = [
        group for group in required_groups if not account_has_group(user, group)
    ]
    groups_changed = bool(missing_account_groups)
    if missing_account_groups:
        privilege = host_privilege_prefix()
        for group in missing_account_groups:
            run(privilege + ["usermod", "-aG", group, user])
        unresolved = [
            group for group in missing_account_groups if not account_has_group(user, group)
        ]
        if unresolved:
            raise RuntimeError(
                "usermod completed but the system still does not report user "
                + user + " in group(s): " + ", ".join(unresolved)
            )
        log_detail(
            "Added user " + user + " to group(s): " + ", ".join(missing_account_groups)
        )

    if groups_changed:
        log_detail(
            "Please log out and log back in as " + user +
            " so the new group membership becomes active, then rerun this command."
        )
        return False

    if os.geteuid() == 0:
        return True

    missing_session_groups = set(required_groups) - effective_group_names()
    if missing_session_groups:
        log_detail(
            "Group membership changes require a new login session before "
            "libvirt can be used. Log out and back in, then run this same "
            "command again. Missing active group(s): "
            + ", ".join(sorted(missing_session_groups))
        )
        return False
    return True


def virsh_command(*arguments: str) -> list[str]:
    """Build a virsh command against the same system daemon as virt-install."""
    return host_privilege_prefix() + ["virsh", "-c", LIBVIRT_URI, *arguments]


def host_package_plan() -> tuple[str, list[str]]:
    """Return the package manager and package names for a supported Linux host."""
    os_release = {}
    try:
        for line in Path("/etc/os-release").read_text(encoding="utf-8").splitlines():
            if "=" in line:
                key, value = line.split("=", 1)
                os_release[key] = value.strip().strip('"')
    except OSError:
        pass

    distro_id = os_release.get("ID", "").lower()
    if distro_id in {"debian", "ubuntu", "linuxmint", "pop"} or shutil_which("apt-get"):
        return "apt-get", [
            "ca-certificates",
            "libvirt-daemon-system",
            "libvirt-clients",
            "virtinst",
            "qemu-utils",
            "qemu-system-x86",
            "genisoimage",
            "openssh-client",
            "psmisc",
            "rsync",
        ]
    if distro_id in {"rhel", "rocky", "almalinux", "fedora", "centos"}:
        manager = "dnf" if shutil_which("dnf") else "yum"
        return manager, [
            "ca-certificates",
            "libvirt",
            "libvirt-client",
            "libvirt-daemon-config-network",
            "virt-install",
            "qemu-kvm",
            "qemu-img",
            "genisoimage",
            "openssh-clients",
            "psmisc",
            "rsync",
        ]
    if distro_id in {"arch", "manjaro", "endeavouros"} or shutil_which("pacman"):
        return "pacman", [
            "ca-certificates",
            "libvirt",
            "virt-install",
            "qemu-img",
            "qemu-desktop",
            "cdrtools",
            "openssh",
            "psmisc",
            "rsync",
        ]
    if shutil_which("dnf"):
        return "dnf", [
            "ca-certificates",
            "libvirt",
            "libvirt-client",
            "virt-install",
            "qemu-kvm",
            "qemu-img",
            "genisoimage",
            "openssh-clients",
            "psmisc",
            "rsync",
        ]
    if shutil_which("yum"):
        return "yum", [
            "ca-certificates",
            "libvirt",
            "libvirt-client",
            "virt-install",
            "qemu-kvm",
            "qemu-img",
            "genisoimage",
            "openssh-clients",
            "psmisc",
            "rsync",
        ]
    raise RuntimeError(
        "cannot install host dependencies automatically: supported package "
        "managers are apt-get, dnf, yum, and pacman"
    )


def install_host_dependencies(*, skip: bool = False) -> None:
    """Install host tools required to create and run the libvirt VMs."""
    required = ("virsh", "virt-install", "qemu-img", "ssh", "ssh-keygen", "rsync")
    missing = [name for name in required if not shutil_which(name)]
    if not any(shutil_which(name) for name in ("genisoimage", "mkisofs")):
        missing.append("genisoimage or mkisofs")
    if not missing:
        return
    if skip:
        raise RuntimeError(
            "missing host command(s): " + ", ".join(missing) +
            " (automatic installation was disabled with --skip-host-deps)"
        )

    package_manager, packages = host_package_plan()
    if os.geteuid() == 0:
        privilege = []
    elif shutil_which("sudo"):
        privilege = ["sudo"]
    else:
        raise RuntimeError(
            "installing host dependencies requires root or the sudo command"
        )

    log_detail("Installing host dependencies for libvirt/KVM: " + ", ".join(packages))
    if package_manager == "apt-get":
        wait_for_host_package_manager(privilege)
        run(privilege + [package_manager, "update"])
        wait_for_host_package_manager(privilege)
        run(privilege + [package_manager, "install", "-y", *packages])
    elif package_manager in {"dnf", "yum"}:
        run(privilege + [package_manager, "install", "-y", *packages])
    else:
        # Refresh Arch's package database without forcing a full system
        # upgrade; the user can still use pacman -Syu separately.
        run(privilege + [package_manager, "-Sy", "--needed", "--noconfirm", *packages])

    # Most distributions activate libvirt through this service/socket.  Do not
    # fail here because service names differ between distro releases; the
    # first virsh operation below will provide the actionable error instead.
    if shutil_which("systemctl"):
        run(privilege + ["systemctl", "enable", "--now", "libvirtd"], check=False)

    remaining = [name for name in required if not shutil_which(name)]
    if not any(shutil_which(name) for name in ("genisoimage", "mkisofs")):
        remaining.append("genisoimage or mkisofs")
    if remaining:
        raise RuntimeError(
            "host dependency installation completed but commands are still "
            "missing: " + ", ".join(remaining)
        )


def host_package_manager_busy(privilege: list[str]) -> bool:
    """Return whether a process currently owns an apt/dpkg lock."""
    lock_paths = [
        "/var/lib/dpkg/lock-frontend",
        "/var/lib/dpkg/lock",
        "/var/cache/apt/archives/lock",
    ]
    fuser = shutil_which("fuser")
    if fuser:
        result = subprocess.run(
            privilege + [fuser, *lock_paths],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
        )
        return result.returncode == 0

    # util-linux is present on many minimal installations even when psmisc
    # is not.  lslocks reports actual kernel-held locks and avoids treating a
    # long-lived helper process as an active apt transaction.
    lslocks = shutil_which("lslocks")
    if lslocks:
        result = subprocess.run(
            privilege + [lslocks, "--noheadings", "--output", "PATH"],
            capture_output=True,
            text=True,
            check=False,
        )
        held_paths = {line.strip() for line in result.stdout.splitlines()}
        return bool(held_paths & set(lock_paths))

    # Do not infer lock ownership from process names. Minimal Ubuntu images
    # often lack fuser, and the persistent unattended-upgrade-shutdown helper
    # can then be mistaken for an active dpkg transaction. The package
    # manager itself remains authoritative; psmisc is included in the package
    # plan so subsequent checks use fuser.
    return False


def wait_for_host_package_manager(privilege: list[str], timeout: int = 900) -> None:
    """Wait for first-boot apt/unattended-upgrades before using apt."""
    if not host_package_manager_busy(privilege):
        return
    log_detail("Waiting for the host's background package operation to finish ...")
    deadline = time.monotonic() + timeout
    while host_package_manager_busy(privilege):
        if time.monotonic() >= deadline:
            raise TimeoutError("timed out waiting for the host apt/dpkg lock")
        time.sleep(5)


def valid_name(value: str, label: str) -> str:
    if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,62}", value):
        raise ValueError(f"invalid {label}: {value!r}")
    return value


def ssh_base(args: argparse.Namespace, node: Node) -> list[str]:
    command = [
        "ssh",
        "-o", "BatchMode=yes",
        "-o", "ConnectTimeout=5",
        "-o", "StrictHostKeyChecking=no",
        "-o", "UserKnownHostsFile=/dev/null",
    ]
    if args.ssh_key:
        command += ["-i", str(args.ssh_key)]
    if args.ssh_jump:
        command += ["-J", args.ssh_jump]
    command.append(f"{args.ssh_user}@{node.ip}")
    return command


def remote_script(args: argparse.Namespace, node: Node, script: str,
                  *, root: bool = False,
                  capture: bool = False) -> subprocess.CompletedProcess[str]:
    command = ssh_base(args, node)
    command += ["sudo", "bash", "-s"] if root else ["bash", "-s"]
    return run(command, input_text=script, capture=capture)


def wait_for_ssh(args: argparse.Namespace, node: Node, timeout: int = 300) -> None:
    log_detail(f"Waiting for SSH on {node.name} ({node.ip}) ...")
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        result = subprocess.run(
            ssh_base(args, node) + ["true"],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
            check=False,
        )
        if result.returncode == 0:
            return
        time.sleep(3)
    raise TimeoutError(f"SSH did not become available on {node.ip} within {timeout}s")


def ensure_network() -> None:
    def network_is_active(info: subprocess.CompletedProcess[str]) -> bool:
        for line in info.stdout.splitlines():
            if ":" not in line:
                continue
            field, value = line.split(":", 1)
            if field.strip().lower() == "active":
                return value.strip().lower() in {"yes", "true", "1"}
        return False

    def start_network() -> None:
        current = run(
            virsh_command("net-info", NETWORK_NAME),
            capture=True,
            check=False,
        )
        if network_is_active(current):
            return
        try:
            run(virsh_command("net-start", NETWORK_NAME))
        except RuntimeError as exc:
            # Another process may have started the network between net-info
            # and net-start. Treat that race as success.
            current = run(
                virsh_command("net-info", NETWORK_NAME),
                capture=True,
                check=False,
            )
            if network_is_active(current):
                return
            raise RuntimeError(
                f"cannot start libvirt network {NETWORK_NAME!r}: libvirt could not "
                f"create bridge {BRIDGE_NAME!r}. The host must provide "
                "CAP_NET_ADMIN to the libvirt daemon. A normal Ubuntu VM can run "
                "nested libvirt, but its outer libvirt host must allow this and "
                "nested KVM should expose /dev/kvm. Check the guest with "
                "'sudo ip link add k8s-cap-test type bridge' and remove it with "
                "'sudo ip link delete k8s-cap-test'. Installing packages alone "
                "cannot provide a missing kernel capability."
            ) from exc

    info = run(virsh_command("net-info", NETWORK_NAME), capture=True, check=False)
    if info.returncode:
        xml = f"""<network>
  <name>{NETWORK_NAME}</name>
  <forward mode='nat'/>
  <bridge name='{BRIDGE_NAME}' stp='on' delay='0'/>
  <ip address='{GATEWAY}' netmask='{NETMASK}'>
    <dhcp>
      <range start='{DHCP_START}' end='{DHCP_END}'/>
      <host mac='{CONTROL_MAC}' name='k8s-cp01' ip='{CONTROL_IP}'/>
      <host mac='{WORKER_MAC}' name='k8s-w01' ip='{WORKER_IP}'/>
    </dhcp>
  </ip>
</network>
"""
        with tempfile.NamedTemporaryFile("w", suffix=".xml") as network_file:
            network_file.write(xml)
            network_file.flush()
            run(virsh_command("net-define", network_file.name))
        start_network()
    elif not network_is_active(info):
        start_network()
    run(virsh_command("net-autostart", NETWORK_NAME))

    # Keep the addresses deterministic even when a guest image does not
    # consume the supplied cloud-init network-config. This is particularly
    # important for NetworkManager-based CentOS images, which may fall back
    # to DHCP during first boot.
    network_xml = run(
        virsh_command("net-dumpxml", NETWORK_NAME), capture=True
    ).stdout
    for mac, name, ip in (
        (CONTROL_MAC, "k8s-cp01", CONTROL_IP),
        (WORKER_MAC, "k8s-w01", WORKER_IP),
    ):
        if mac.lower() in network_xml.lower():
            continue
        host_xml = f"<host mac='{mac}' name='{name}' ip='{ip}'/>"
        run(virsh_command(
            "net-update", NETWORK_NAME, "add", "ip-dhcp-host", host_xml,
            "--live", "--config",
        ))


def cloud_init_files(
    directory: Path, node: Node, args: argparse.Namespace
) -> tuple[Path, Path, Path]:
    key = args.ssh_public_key.read_text(encoding="utf-8").strip()
    if not key:
        raise ValueError(f"SSH public key is empty: {args.ssh_public_key}")

    admin_group = GUEST_ADMIN_GROUP
    if admin_group == "auto":
        centos_variants = ("centos", "rhel", "rocky", "almalinux", "fedora")
        admin_group = (
            "wheel" if GUEST_OS_VARIANT.lower().startswith(centos_variants)
            else "sudo"
        )

    interface_match = GUEST_INTERFACE_MATCH
    if interface_match == "auto":
        centos_variants = ("centos", "rhel", "rocky", "almalinux", "fedora")
        interface_match = (
            "eth*" if GUEST_OS_VARIANT.lower().startswith(centos_variants)
            else "en*"
        )

    # JSON string quoting is also valid YAML and avoids depending on PyYAML.
    user_data = f"""#cloud-config
hostname: {node.name}
manage_etc_hosts: true
users:
  - default
  - name: {args.ssh_user}
    gecos: Kubernetes administrator
    groups: [{admin_group}]
    shell: /bin/bash
    sudo: ["ALL=(ALL) NOPASSWD:ALL"]
    ssh_authorized_keys: [{json.dumps(key)}]
ssh_pwauth: false
disable_root: true
"""
    network_config = f"""version: 2
ethernets:
  primary:
    match:
      name: {interface_match}
    dhcp4: false
    addresses: [{node.ip}/24]
    routes:
      - to: 0.0.0.0/0
        via: {GATEWAY}
    nameservers:
      addresses: [{DNS_SERVERS}]
"""
    user_file = directory / f"{node.name}-user-data"
    metadata_file = directory / f"{node.name}-meta-data"
    network_file = directory / f"{node.name}-network-config"
    user_file.write_text(user_data, encoding="utf-8")
    metadata_file.write_text(
        f"instance-id: {node.name}\nlocal-hostname: {node.name}\n",
        encoding="utf-8",
    )
    network_file.write_text(network_config, encoding="utf-8")
    return user_file, metadata_file, network_file


def qemu_image_info(image: Path) -> dict[str, object]:
    result = run(
        host_privilege_prefix() + ["qemu-img", "info", "--output=json", str(image)],
        capture=True,
    )
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError as exc:
        raise RuntimeError(f"could not read qemu image information: {image}") from exc


def base_image_format(base_image: Path) -> str:
    try:
        image_format = qemu_image_info(base_image)["format"]
    except KeyError as exc:
        raise RuntimeError(f"could not determine image format: {base_image}") from exc
    return str(image_format)


def ensure_storage_dir(storage_dir: Path) -> None:
    if not storage_dir.exists():
        run(host_privilege_prefix() + ["mkdir", "-p", str(storage_dir)])


def default_image_path(image_url: str, storage_dir: Path) -> Path:
    parsed = urlparse(image_url)
    if parsed.scheme not in {"http", "https"}:
        raise RuntimeError("--base-image-url must use http:// or https://")
    filename = Path(parsed.path).name
    if not filename or filename in {".", ".."}:
        raise RuntimeError("--base-image-url does not contain an image filename")
    return storage_dir / filename


def ensure_base_image(args: argparse.Namespace) -> None:
    """Download the VM backing image when it is not available locally."""
    image = args.base_image
    if image is None:
        image = default_image_path(args.base_image_url, args.storage_dir)
        args.base_image = image

    if image.is_file():
        args.base_image = image.resolve()
        return
    if not args.base_image_url:
        raise RuntimeError(
            f"base image does not exist: {image}; provide --base-image-url"
        )
    if not image.parent.is_dir():
        raise RuntimeError(f"base image directory does not exist: {image.parent}")

    log_detail(f"Downloading base image from {args.base_image_url} to {image} ...")
    temporary_path: Path | None = None
    try:
        with tempfile.NamedTemporaryFile(
            prefix="k8s-base-image-", suffix=".download", delete=False
        ) as temporary_file:
            temporary_path = Path(temporary_file.name)
            request = Request(
                args.base_image_url,
                headers={"User-Agent": "install-k8s-cluster/1.0"},
            )
            with urlopen(request, timeout=60) as response:
                while True:
                    chunk = response.read(1024 * 1024)
                    if not chunk:
                        break
                    temporary_file.write(chunk)

        if temporary_path.stat().st_size == 0:
            raise RuntimeError("downloaded base image is empty")
        run(host_privilege_prefix() + [
            "install", "-m", "0644", str(temporary_path), str(image),
        ])
    except OSError as exc:
        raise RuntimeError(
            f"could not download base image from {args.base_image_url}: {exc}"
        ) from exc
    finally:
        if temporary_path is not None:
            temporary_path.unlink(missing_ok=True)

    args.base_image = image.resolve()


def domain_exists(name: str) -> bool:
    return run(virsh_command("dominfo", name), capture=True, check=False).returncode == 0


def ensure_vm_autostart(name: str) -> None:
    """Enable libvirt autostart for a cluster VM, including existing VMs."""
    run(virsh_command("autostart", name))


def ensure_vm(node: Node, args: argparse.Namespace, cloud_dir: Path,
              image_format: str | None) -> None:
    if domain_exists(node.name):
        log_detail(f"VM {node.name} already exists; keeping its definition")
        ensure_vm_autostart(node.name)
        return
    if args.base_image is None or image_format is None:
        raise RuntimeError("--base-image is required when creating VMs")

    disk = args.storage_dir / f"{node.name}.qcow2"
    if not disk.exists():
        run(host_privilege_prefix() + [
            "qemu-img", "create", "-f", "qcow2", "-F", image_format,
            "-b", str(args.base_image), str(disk),
        ])

    disk_info = qemu_image_info(disk)
    try:
        current_size = int(disk_info["virtual-size"])
    except (KeyError, TypeError, ValueError) as exc:
        raise RuntimeError(f"could not determine virtual size of {disk}") from exc
    requested_size = args.disk_gib * 1024**3
    if current_size < requested_size:
        run(host_privilege_prefix() + ["qemu-img", "resize", str(disk), f"{args.disk_gib}G"])
    elif current_size > requested_size:
        current_gib = current_size / 1024**3
        log_detail(
            f"Using existing {current_gib:.1f} GiB disk for {node.name}; "
            f"it cannot be safely shrunk to {args.disk_gib} GiB because it "
            "uses the base image as a backing file."
        )

    user_file, metadata_file, network_file = cloud_init_files(cloud_dir, node, args)
    run(host_privilege_prefix() + [
        "virt-install",
        "--connect", "qemu:///system",
        "--name", node.name,
        "--memory", str(node.memory_mib),
        "--vcpus", str(node.vcpus),
        "--disk", f"path={disk},format=qcow2,bus=virtio",
        "--network", f"network={NETWORK_NAME},model=virtio,mac={node.mac}",
        "--os-variant", GUEST_OS_VARIANT,
        "--import",
        "--graphics", "none",
        "--console", "pty,target_type=serial",
        "--noautoconsole",
        "--cloud-init",
        f"user-data={user_file},meta-data={metadata_file},network-config={network_file}",
    ])
    ensure_vm_autostart(node.name)


def node_setup_script(k8s_version: str) -> str:
    return f"""set -euo pipefail
export DEBIAN_FRONTEND=noninteractive

package_manager_busy() {{
  if command -v fuser >/dev/null 2>&1; then
    fuser /var/lib/dpkg/lock-frontend /var/lib/dpkg/lock \\
      /var/cache/apt/archives/lock >/dev/null 2>&1
    # The lock files can remain on disk after the process exits.  When fuser
    # is available, only an actual process holding one of them is relevant;
    # do not fall through to a broad process-name check.
    return $?
  fi
  if command -v lslocks >/dev/null 2>&1; then
    lslocks --noheadings --output PATH 2>/dev/null \\
      | grep -Fqx -e /var/lib/dpkg/lock-frontend \\
                    -e /var/lib/dpkg/lock \\
                    -e /var/cache/apt/archives/lock
    return $?
  fi
  # Do not use process-name matching here. Ubuntu's persistent
  # unattended-upgrade-shutdown helper is not a dpkg lock owner.
  return 1
}}

wait_for_package_manager() {{
  local remaining=900
  if package_manager_busy; then
    echo "Waiting for Ubuntu's background package operation to finish ..."
  fi
  while package_manager_busy; do
    if [ "$remaining" -le 0 ]; then
      echo "Timed out waiting for the dpkg/apt lock" >&2
      exit 1
    fi
    sleep 5
    remaining=$((remaining - 5))
  done
}}

swapoff -a
sed -ri '/[[:space:]]swap[[:space:]]/ s/^/#/' /etc/fstab

cat >/etc/modules-load.d/k8s.conf <<'EOF'
overlay
br_netfilter
EOF
modprobe overlay
modprobe br_netfilter

cat >/etc/sysctl.d/k8s.conf <<'EOF'
net.bridge.bridge-nf-call-iptables = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward = 1
EOF
# Apply only the Kubernetes settings. Applying every sysctl file on the guest
# also replays unrelated host/image settings, some of which are invalid on
# newer kernels and can interfere with nested-VM troubleshooting.
sysctl -p /etc/sysctl.d/k8s.conf

if command -v apt-get >/dev/null 2>&1; then
  wait_for_package_manager
  apt-get update
  wait_for_package_manager
  apt-get install -y ca-certificates curl gnupg gpg apt-transport-https psmisc
  install -m 0755 -d /etc/apt/keyrings

  curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
    | gpg --dearmor --yes -o /etc/apt/keyrings/docker.gpg
  echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
    https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \
    >/etc/apt/sources.list.d/docker.list
  wait_for_package_manager
  apt-get update
  wait_for_package_manager
  apt-get install -y containerd.io

  curl -fsSL https://pkgs.k8s.io/core:/stable:/{k8s_version}/deb/Release.key \
    | gpg --dearmor --yes -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg
  echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] \
    https://pkgs.k8s.io/core:/stable:/{k8s_version}/deb/ /" \
    >/etc/apt/sources.list.d/kubernetes.list
  wait_for_package_manager
  apt-get update
  wait_for_package_manager
  apt-get install -y kubelet kubeadm kubectl
  apt-mark hold kubelet kubeadm kubectl
elif command -v dnf >/dev/null 2>&1; then
  echo "Detected a DNF-based guest; installing CentOS/RHEL Kubernetes prerequisites ..."
  dnf install -y \
    ca-certificates curl gnupg2 iptables iproute-tc ipset conntrack-tools \
    socat ebtables ethtool psmisc dnf-plugins-core

  curl -fsSL https://download.docker.com/linux/centos/docker-ce.repo \
    -o /etc/yum.repos.d/docker-ce.repo
  dnf install -y containerd.io

  # Kubernetes requires either an SELinux policy configured for the workload
  # or permissive mode.  This lab installer uses permissive mode for the
  # minimal CentOS image, matching the usual kubeadm test setup.
  setenforce 0 || true
  if [ -f /etc/selinux/config ]; then
    sed -i -E 's/^[[:space:]]*SELINUX=.*/SELINUX=permissive/' /etc/selinux/config
  fi
  systemctl disable --now firewalld 2>/dev/null || true

  cat >/etc/yum.repos.d/kubernetes.repo <<'EOF'
[kubernetes]
name=Kubernetes
baseurl=https://pkgs.k8s.io/core:/stable:/{k8s_version}/rpm/
enabled=1
gpgcheck=1
gpgkey=https://pkgs.k8s.io/core:/stable:/{k8s_version}/rpm/repodata/repomd.xml.key
exclude=kubelet kubeadm kubectl cri-tools kubernetes-cni
EOF
  dnf install -y kubelet kubeadm kubectl --disableexcludes=kubernetes
  dnf versionlock add kubelet kubeadm kubectl >/dev/null 2>&1 || true
else
  echo "Unsupported guest: neither apt-get nor dnf is available" >&2
  exit 1
fi

containerd config default >/etc/containerd/config.toml
# The CRI plugin must be enabled for kubeadm/containerd integration.  Some
# packaged containerd configurations disable it because they are intended for
# Docker-only use.
sed -i -E 's/^[[:space:]]*disabled_plugins[[:space:]]*=.*/disabled_plugins = []/' /etc/containerd/config.toml
sed -i 's/SystemdCgroup = false/SystemdCgroup = true/' /etc/containerd/config.toml
systemctl enable containerd
systemctl restart containerd

echo "Waiting for containerd CRI plugin ..."
for attempt in $(seq 1 {CONTAINERD_CRI_READY_TIMEOUT_SECONDS // 2}); do
  if ctr plugins ls 2>/dev/null \
      | grep -Eq 'io[.]containerd[.]grpc[.]v1[[:space:]]+cri[[:space:]]+.*[[:space:]]ok[[:space:]]*$'; then
    break
  fi
  if [ "$attempt" -eq {CONTAINERD_CRI_READY_TIMEOUT_SECONDS // 2} ]; then
    echo "containerd CRI plugin is not ready" >&2
    ctr plugins ls >&2 || true
    journalctl -u containerd --no-pager -n 100 >&2 || true
    exit 1
  fi
  sleep 2
done

systemctl enable kubelet
"""


def initialize_control_plane(args: argparse.Namespace, control: Node) -> None:
    script = f"""set -euo pipefail
if [ ! -f /etc/kubernetes/admin.conf ]; then
  kubeadm init \\
    --pod-network-cidr={POD_CIDR} \\
    --apiserver-advertise-address={control.ip} \\
    --control-plane-endpoint={CONTROL_PLANE_ENDPOINT} \\
    --cri-socket=unix:///run/containerd/containerd.sock
fi

# Keep the kubeadm client configuration aligned with the endpoint selected by
# this installer.  This also repairs an admin.conf left by an earlier/manual
# initialization without changing certificates or the running API server.
for kubeconfig in \\
    /etc/kubernetes/admin.conf \\
    /etc/kubernetes/super-admin.conf \\
    /etc/kubernetes/bootstrap-kubelet.conf \\
    /etc/kubernetes/kubelet.conf \\
    /etc/kubernetes/controller-manager.conf \\
    /etc/kubernetes/scheduler.conf \\
    /var/lib/kubelet/kubeconfig; do
  if [ -f "$kubeconfig" ]; then
    sed -i -E 's#^[[:space:]]*server:[[:space:]]*https://[^[:space:]]+#    server: https://{CONTROL_PLANE_ENDPOINT}#' \\
      "$kubeconfig"
  fi
done
if ! grep -Fqx '    server: https://{CONTROL_PLANE_ENDPOINT}' /etc/kubernetes/admin.conf; then
  echo "admin.conf does not point to https://{CONTROL_PLANE_ENDPOINT}" >&2
  exit 1
fi
systemctl restart kubelet

KUBE_HOME=$(getent passwd {args.ssh_user} | cut -d: -f6)
install -d -o {args.ssh_user} -g {args.ssh_user} -m 700 "$KUBE_HOME/.kube"
chown {args.ssh_user}:{args.ssh_user} "$KUBE_HOME/.kube"
chmod 700 "$KUBE_HOME/.kube"
install -o {args.ssh_user} -g {args.ssh_user} -m 600 /etc/kubernetes/admin.conf "$KUBE_HOME/.kube/config"

echo "Waiting for the Kubernetes API server at https://{CONTROL_PLANE_ENDPOINT} ..."
for attempt in $(seq 1 60); do
  if curl --silent --show-error --insecure --fail --max-time 3 \\
      https://{CONTROL_PLANE_ENDPOINT}/readyz >/dev/null; then
    break
  fi
  if [ "$attempt" -eq 60 ]; then
    echo "Kubernetes API server did not become ready" >&2
    systemctl --no-pager --full status kubelet || true
    journalctl -u kubelet --no-pager -n 100 || true
    exit 1
  fi
  sleep 5
done
"""
    remote_script(args, control, script, root=True)


def control_plane_join_command(args: argparse.Namespace, control: Node) -> list[str]:
    # Do not let kubeadm select a stale root/user kubeconfig (for example
    # /root/.kube/config inherited from a customized base image).  The
    # admin.conf generated for this cluster is the authoritative API endpoint.
    command = ssh_base(args, control) + [
        "sudo", "env", "-u", "KUBECONFIG", "kubeadm", "token", "create",
        f"--kubeconfig={KUBEADM_KUBECONFIG}", "--print-join-command",
    ]
    result = run(command, capture=True)
    lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    if not lines or not lines[-1].startswith("kubeadm join "):
        raise RuntimeError("could not obtain kubeadm join command")
    join = shlex.split(lines[-1])
    if len(join) < 3 or join[:2] != ["kubeadm", "join"]:
        raise RuntimeError("unexpected kubeadm join command")
    return join + ["--cri-socket=unix:///run/containerd/containerd.sock"]


def join_worker(args: argparse.Namespace, worker: Node, join_command: list[str]) -> None:
    script = "set -euo pipefail\n"
    script += "if [ ! -f /etc/kubernetes/kubelet.conf ]; then\n"
    script += "  " + shlex.join(join_command) + "\n"
    script += "fi\n"
    remote_script(args, worker, script, root=True)


def create_external_access_token(args: argparse.Namespace, control: Node) -> str:
    """Create an idempotent cluster-admin service-account token for integrations."""
    script = f"""set -euo pipefail
kubectl apply --server-side --force-conflicts \\
  --request-timeout={KUBECTL_REQUEST_TIMEOUT_SECONDS}s -f - <<'YAML'
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {EXTERNAL_ACCESS_SERVICE_ACCOUNT}
  namespace: {EXTERNAL_ACCESS_NAMESPACE}
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: {EXTERNAL_ACCESS_SERVICE_ACCOUNT}-cluster-admin
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: {EXTERNAL_ACCESS_SERVICE_ACCOUNT}
  namespace: {EXTERNAL_ACCESS_NAMESPACE}
---
apiVersion: v1
kind: Secret
metadata:
  name: {EXTERNAL_ACCESS_SECRET}
  namespace: {EXTERNAL_ACCESS_NAMESPACE}
  annotations:
    kubernetes.io/service-account.name: {EXTERNAL_ACCESS_SERVICE_ACCOUNT}
type: kubernetes.io/service-account-token
YAML

for attempt in $(seq 1 60); do
  token=$(kubectl -n {EXTERNAL_ACCESS_NAMESPACE} get secret {EXTERNAL_ACCESS_SECRET} \\
    -o jsonpath='{{.data.token}}' 2>/dev/null | base64 -d 2>/dev/null || true)
  if [ -n "$token" ]; then
    printf '%s\\n' "$token"
    exit 0
  fi
  sleep 2
done
echo "Timed out waiting for the external access service-account token" >&2
exit 1
"""
    result = remote_script(args, control, script, capture=True)
    candidates = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    if not candidates:
        raise RuntimeError("external access token was not returned")
    token = candidates[-1]
    if len(token.split(".")) != 3:
        raise RuntimeError("external access token has an unexpected format")
    return token


def kubectl_script(args: argparse.Namespace, control: Node, script: str) -> None:
    remote_script(args, control, script)


def install_addons(args: argparse.Namespace, control: Node) -> None:
    calico_url = (
        f"https://raw.githubusercontent.com/projectcalico/calico/{args.calico_version}/"
        "manifests/tigera-operator.yaml"
    )
    metallb_url = (
        f"https://raw.githubusercontent.com/metallb/metallb/{args.metallb_version}/"
        "config/manifests/metallb-native.yaml"
    )
    script = f"""set -euo pipefail
export KUBECONFIG="$HOME/.kube/config"

# Large CRDs can exceed the 256 KiB limit of kubectl's client-side
# last-applied-configuration annotation. Server-side apply stores field
# ownership separately and is also safe to repeat after a partial install.
kubectl_apply() {{
  kubectl apply --server-side --force-conflicts \\
    --request-timeout={KUBECTL_REQUEST_TIMEOUT_SECONDS}s \\
    --field-manager=install-k8s-cluster "$@"
}}

kubectl_apply_retry() {{
  local attempt
  for attempt in $(seq 1 {CALICO_MANIFEST_APPLY_RETRIES}); do
    if kubectl_apply "$@"; then
      return 0
    fi
    if [ "$attempt" -lt {CALICO_MANIFEST_APPLY_RETRIES} ]; then
      echo "Calico manifest apply was not completed; retrying ($attempt/{CALICO_MANIFEST_APPLY_RETRIES}) ..." >&2
      sleep 10
    fi
  done
  return 1
}}

if kubectl -n tigera-operator get deployment tigera-operator >/dev/null 2>&1; then
  echo "Calico operator is already present; skipping the manifest re-apply."
else
  kubectl_apply_retry -f {calico_url}
fi
echo "Waiting for Calico Installation CRD to become established ..."
for attempt in $(seq 1 36); do
  established=$(kubectl get crd installations.operator.tigera.io \
      -o jsonpath='{{.status.conditions[?(@.type=="Established")].status}}' \
      2>/dev/null || true)
  if [ "$established" = "True" ]; then
    break
  fi
  if [ "$attempt" -eq 36 ]; then
    echo "Timed out waiting for Calico Installation CRD" >&2
    kubectl get crd installations.operator.tigera.io -o yaml || true
    kubectl get events --sort-by=.lastTimestamp | tail -50 || true
    exit 1
  fi
  sleep 5
done
kubectl_apply -f - <<'YAML'
apiVersion: operator.tigera.io/v1
kind: Installation
metadata:
  name: default
spec:
  calicoNetwork:
    nodeAddressAutodetectionV4:
      cidrs:
        - {SUBNET}
    ipPools:
      - blockSize: 26
        cidr: {POD_CIDR}
        encapsulation: VXLAN
        natOutgoing: Enabled
        nodeSelector: all()
YAML
kubectl -n tigera-operator rollout status deployment/tigera-operator --timeout=180s

# The operator creates calico-system asynchronously after the Installation
# resource is accepted. Do not query the namespace/DaemonSet immediately:
# kubectl would otherwise fail with "namespaces calico-system not found" on a
# normal, healthy installation.
echo "Waiting for Calico to create namespace calico-system ..."
for attempt in $(seq 1 60); do
  if kubectl get namespace calico-system >/dev/null 2>&1; then
    break
  fi
  if [ "$attempt" -eq 60 ]; then
    echo "Timed out waiting for namespace calico-system" >&2
    kubectl get tigerastatus || true
    kubectl get installation.operator.tigera.io/default -o yaml || true
    kubectl -n tigera-operator logs deployment/tigera-operator --tail=100 || true
    kubectl get events -A --sort-by=.lastTimestamp | tail -50 || true
    exit 1
  fi
  sleep 5
done

echo "Waiting for Calico DaemonSet calico-node ..."
for attempt in $(seq 1 60); do
  if kubectl -n calico-system get daemonset calico-node >/dev/null 2>&1; then
    break
  fi
  if [ "$attempt" -eq 60 ]; then
    echo "Timed out waiting for DaemonSet calico-node" >&2
    kubectl get tigerastatus || true
    kubectl get installation.operator.tigera.io/default -o yaml || true
    kubectl -n tigera-operator logs deployment/tigera-operator --tail=100 || true
    kubectl get events -A --sort-by=.lastTimestamp | tail -50 || true
    exit 1
  fi
  sleep 5
done

calico_diagnostics() {{
  kubectl get nodes -o wide || true
  kubectl get tigerastatus || true
  kubectl get installation.operator.tigera.io/default \
    -o 'custom-columns=NAME:.metadata.name,DEGRADED:.status.conditions[?(@.type=="Degraded")].status,REASON:.status.conditions[?(@.type=="Degraded")].reason,MESSAGE:.status.conditions[?(@.type=="Degraded")].message' \
    --no-headers || true
  kubectl -n calico-system get pods -o wide || true
  kubectl -n calico-system get daemonset calico-node \
    -o custom-columns=NAME:.metadata.name,DESIRED:.status.desiredNumberScheduled,READY:.status.numberReady,AVAILABLE:.status.numberAvailable,UNAVAILABLE:.status.numberUnavailable \
    --no-headers || true
  for pod in $(kubectl -n calico-system get pods -l k8s-app=calico-node \
      -o name 2>/dev/null || true); do
    kubectl -n calico-system describe "$pod" || true
    kubectl -n calico-system logs "$pod" --all-containers --tail=100 || true
  done
  kubectl get events -A --sort-by=.lastTimestamp | tail -100 || true
}}

if ! kubectl -n calico-system rollout status daemonset/calico-node --timeout={CALICO_ROLLOUT_TIMEOUT_SECONDS}s; then
  echo "Calico DaemonSet did not become ready; collecting diagnostics ..." >&2
  calico_diagnostics
  exit 1
fi

# CoreDNS is installed by kubeadm before the CNI is ready. It normally becomes
# ready by itself once Calico is running; restarting it here can leave an old
# pod stuck in Terminating and make an otherwise healthy installation fail.
echo "Waiting for CoreDNS to become ready ..."
# Clean up a terminating CoreDNS pod left by an earlier interrupted run
# before waiting, so a rerun does not spend five minutes on the same stale
# Deployment revision.
for pod in $(kubectl -n kube-system get pods -l k8s-app=kube-dns \
    -o custom-columns=NAME:.metadata.name,DELETING:.metadata.deletionTimestamp \
    --no-headers | awk '$2 != "<none>" && $2 != "" {{print $1}}'); do
  kubectl -n kube-system delete pod "$pod" --grace-period=0 --force || true
done

if ! kubectl -n kube-system rollout status deployment/coredns --timeout=300s; then
  echo "CoreDNS rollout did not finish; inspecting and removing only stuck CoreDNS pods ..." >&2
  kubectl -n kube-system get pods -l k8s-app=kube-dns -o wide || true
  kubectl -n kube-system describe deployment/coredns || true
  kubectl get nodes -o wide || true

  # A CoreDNS pod is stateless. If the previous run left one in Terminating,
  # force-remove that pod so the Deployment controller can converge.
  for pod in $(kubectl -n kube-system get pods -l k8s-app=kube-dns \
      -o custom-columns=NAME:.metadata.name,DELETING:.metadata.deletionTimestamp \
      --no-headers | awk '$2 != "<none>" && $2 != "" {{print $1}}'); do
    kubectl -n kube-system delete pod "$pod" --grace-period=0 --force || true
  done
  kubectl -n kube-system rollout status deployment/coredns --timeout=300s
fi

if kubectl -n metallb-system get deployment controller >/dev/null 2>&1; then
  echo "MetalLB controller is already present; skipping the manifest re-apply."
else
  kubectl_apply -f {metallb_url}
fi
if ! kubectl -n metallb-system rollout status deployment/controller --timeout={METALLB_ROLLOUT_TIMEOUT_SECONDS}s; then
  echo "MetalLB controller did not become ready; collecting diagnostics ..." >&2
  kubectl -n metallb-system get pods,svc,endpoints -o wide || true
  kubectl -n metallb-system describe deployment/controller || true
  kubectl -n metallb-system logs deployment/controller --all-containers --tail=200 || true
  kubectl get events -A --sort-by=.lastTimestamp | tail -100 || true
  exit 1
fi

# MetalLB's validating webhook is served by the controller pod. Deployment
# readiness can be reported before the Service endpoint is reachable, so wait
# briefly for the endpoint and retry the custom resources while the webhook
# finishes starting.
echo "Waiting for MetalLB webhook endpoint ..."
for attempt in $(seq 1 36); do
  webhook_ips=$(kubectl -n metallb-system get endpoints metallb-webhook-service \
      -o jsonpath='{{.subsets[*].addresses[*].ip}}' 2>/dev/null || true)
  if [ -n "$webhook_ips" ]; then
    break
  fi
  if [ "$attempt" -eq 36 ]; then
    echo "Timed out waiting for MetalLB webhook endpoint" >&2
    kubectl -n metallb-system get pods,svc,endpoints metallb-webhook-service -o wide || true
    kubectl -n metallb-system logs deployment/controller --all-containers --tail=100 || true
    exit 1
  fi
  sleep 5
done

for attempt in $(seq 1 36); do
  if kubectl_apply -f - <<'YAML'
apiVersion: metallb.io/v1beta1
kind: IPAddressPool
metadata:
  name: default-pool
  namespace: metallb-system
spec:
  addresses:
    - {METALLB_START}-{METALLB_END}
---
apiVersion: metallb.io/v1beta1
kind: L2Advertisement
metadata:
  name: default-l2
  namespace: metallb-system
spec:
  ipAddressPools:
    - default-pool
YAML
  then
    break
  fi
  if [ "$attempt" -eq 36 ]; then
    echo "Timed out applying MetalLB address pool and L2 advertisement" >&2
    kubectl -n metallb-system get pods,svc,endpoints metallb-webhook-service -o wide || true
    kubectl -n metallb-system logs deployment/controller --all-containers --tail=100 || true
    exit 1
  fi
  echo "MetalLB webhook is not ready yet; retrying in 5 seconds ..." >&2
  sleep 5
done

kubectl_apply -f https://raw.githubusercontent.com/rancher/local-path-provisioner/v0.0.31/deploy/local-path-storage.yaml
kubectl patch storageclass local-path -p '{{"metadata":{{"annotations":{{"storageclass.kubernetes.io/is-default-class":"true"}}}}}}'
kubectl get nodes -o wide
"""
    kubectl_script(args, control, script)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-image", type=Path,
                        help="local VM backing image path; downloaded there if missing")
    parser.add_argument(
        "--base-image-url",
        default=DEFAULT_BASE_IMAGE_URL,
        help=(
            "URL used to download the base image when it is missing "
            f"(default: {DEFAULT_BASE_IMAGE_URL})"
        ),
    )
    parser.add_argument("--storage-dir", type=Path,
                        default=Path("/var/lib/libvirt/images"),
                        help="directory for VM overlay disks (default: /var/lib/libvirt/images)")
    parser.add_argument(
        "--log-file", type=Path, default=Path(LOG_FILE_NAME),
        help=f"append detailed output to this file (default: {LOG_FILE_NAME})",
    )
    parser.add_argument("--disk-gib", type=int, default=60,
                        help="size of each VM overlay disk (default: 60)")
    parser.add_argument("--ssh-user", default="devops",
                        help="cloud-init and SSH user (default: devops)")
    parser.add_argument("--ssh-key", type=Path,
                        help="private SSH key; defaults to ~/.ssh/id_ed25519 and is generated if missing")
    parser.add_argument("--ssh-public-key", type=Path,
                        help="public key for cloud-init (default: --ssh-key + .pub; generated if missing)")
    parser.add_argument("--ssh-jump",
                        help="optional SSH ProxyJump value, for example root@host")
    parser.add_argument("--skip-vm-create", action="store_true",
                        help="configure existing VMs instead of creating them")
    parser.add_argument("--skip-host-deps", action="store_true",
                        help="do not install missing host packages automatically")
    parser.add_argument("--skip-addons", action="store_true",
                        help="stop after kubeadm join; do not install CNI/add-ons")
    parser.add_argument("--k8s-version", default="v1.32",
                        help="pkgs.k8s.io minor channel (default: v1.32)")
    parser.add_argument("--calico-version", default="v3.29.0")
    parser.add_argument("--metallb-version", default="v0.14.9")
    args = parser.parse_args()

    args.ssh_user = valid_name(args.ssh_user, "SSH user")
    key_home = Path.home()
    if os.environ.get("SUDO_USER"):
        try:
            key_home = Path(pwd.getpwnam(os.environ["SUDO_USER"]).pw_dir)
        except KeyError:
            pass
    if args.ssh_key is None:
        for candidate in (key_home / ".ssh/id_ed25519", key_home / ".ssh/id_rsa"):
            if candidate.exists():
                args.ssh_key = candidate
                break
    if args.ssh_key is None:
        args.ssh_key = key_home / ".ssh/id_ed25519"
    args.ssh_key = args.ssh_key.expanduser()
    if args.ssh_public_key is None:
        args.ssh_public_key = Path(str(args.ssh_key) + ".pub")
    args.ssh_public_key = args.ssh_public_key.expanduser()
    if args.disk_gib < 20:
        parser.error("--disk-gib must be at least 20")
    if args.base_image is not None:
        args.base_image = args.base_image.resolve()
    args.storage_dir = args.storage_dir.resolve()
    args.log_file = args.log_file.expanduser().resolve()
    return args


def print_success_summary(args: argparse.Namespace, nodes: tuple[Node, ...],
                         join_command: list[str], token: str | None) -> None:
    print("\nKubernetes cluster installation completed successfully.")
    print("\nNodes:")
    for node in nodes:
        print(f"  {node.name:<12} {node.role:<14} {node.ip}")

    print("\nCluster IP plan:")
    print(f"  Node/libvirt network : {SUBNET} (gateway {GATEWAY})")
    print(f"  DHCP range           : {DHCP_START}-{DHCP_END}")
    print(f"  Kubernetes API       : https://{CONTROL_PLANE_ENDPOINT}")
    print(f"  Pod network (Calico) : {POD_CIDR}")
    print(f"  LoadBalancer range   : {METALLB_START}-{METALLB_END}")

    print("\nAdd another worker on a prepared host by running as root:")
    print("  sudo " + shlex.join(join_command))

    if token:
        print("\nExternal controller access:")
        print(f"  API endpoint : https://{CONTROL_PLANE_ENDPOINT}")
        print("  Bearer token : " + token)
        print("  Token scope  : cluster-admin; protect this token")
        print("  CA file      : /etc/kubernetes/pki/ca.crt on k8s-cp01")
    else:
        print("\nExternal controller access: not generated (--skip-addons was used).")

    print(f"\nDetailed append-only log: {args.log_file}")


def main() -> int:
    args = parse_args()
    configure_logging(args.log_file)
    try:
        authenticate_sudo()
        with progress_step("Install host dependencies and verify tools"):
            install_host_dependencies(skip=args.skip_host_deps)
            require_commands()

        with progress_step("Prepare SSH credentials"):
            ensure_ssh_keypair(args)

        with progress_step("Configure host permissions"):
            permissions_ready = ensure_host_groups()
        if not permissions_ready:
            print(
                f"\nLogoff/logon required for host group changes. "
                f"Log back in as {login_user()} and rerun the installer."
            )
            print(f"Detailed append-only log: {args.log_file}")
            return 0

        control = Node(
            "k8s-cp01", CONTROL_IP, "control-plane", CONTROL_PLANE_MEMORY_MIB,
            mac=CONTROL_MAC,
        )
        worker = Node(
            "k8s-w01", WORKER_IP, "worker", WORKER_MEMORY_MIB,
            mac=WORKER_MAC,
        )
        nodes = (control, worker)

        with progress_step("Prepare libvirt network and storage"):
            ensure_network()
            ensure_storage_dir(args.storage_dir)

        needs_base_image = (
            not args.skip_vm_create
            and any(not domain_exists(node.name) for node in nodes)
        )
        if needs_base_image:
            with progress_step("Download or verify the VM base image"):
                ensure_base_image(args)
        image_format = base_image_format(args.base_image) if args.base_image else None

        with progress_step("Create or reuse cluster VMs"):
            with tempfile.TemporaryDirectory(prefix="k8s-cloud-init-") as temp_dir:
                cloud_dir = Path(temp_dir)
                if not args.skip_vm_create:
                    for node in nodes:
                        ensure_vm(node, args, cloud_dir, image_format)
                # The temporary cloud-init files are no longer needed after
                # virt-install has created both domains.

        with progress_step("Wait for SSH on both cluster VMs"):
            for node in nodes:
                wait_for_ssh(args, node)

        with progress_step("Configure Kubernetes node prerequisites"):
            setup = node_setup_script(args.k8s_version)
            for node in nodes:
                remote_script(args, node, setup, root=True)

        with progress_step("Initialize the control-plane"):
            initialize_control_plane(args, control)

        with progress_step("Generate the worker join command"):
            join_command = control_plane_join_command(args, control)

        with progress_step("Join the worker node"):
            join_worker(args, worker, join_command)

        if not args.skip_addons:
            with progress_step("Install Calico, MetalLB, and local-path storage"):
                install_addons(args, control)

        token = None
        if not args.skip_addons:
            with progress_step("Create external controller access credentials"):
                token = create_external_access_token(args, control)

        print_success_summary(args, nodes, join_command, token)
        return 0
    except Exception as exc:
        log_detail(f"ERROR: {exc}")
        log_detail(traceback.format_exc())
        print(f"\nInstallation failed. See the detailed log: {args.log_file}")
        return 1
    finally:
        close_logging()


if __name__ == "__main__":
    raise SystemExit(main())
