#!/usr/bin/python3

import argparse
import os
import re
import shutil
import stat
from pathlib import Path

from aib_postprocess import (
    QM_VAR_TMPFILES,
    ensure_file_contents,
    resolve_in_root,
    split_qm_tmpfiles,
    tmpfiles_escape,
    tmpfiles_fields,
)

AUTOVAR = "aib-composefs-var.conf"
AUTOVAR_HEADER = "# Generated by composefs_postprocess.\n"


def clear_directory(path):
    for child in path.iterdir():
        if child.is_dir() and not child.is_symlink():
            shutil.rmtree(child)
        else:
            child.unlink()


def cleanup(root):
    """Remove known build residue, preserving initial application state in /var."""
    # /run and /tmp can contain build-time residue.
    for name in ("run", "tmp"):
        clear_directory(root / name)

    # Leftover junk in /etc
    for name in (
        ".pwd.lock",
        "passwd-",
        "group-",
        "shadow-",
        "gshadow-",
        "subuid-",
        "subgid-",
    ):
        (root / "etc" / name).unlink(missing_ok=True)

    # semodule's store has already moved to /etc/selinux.
    for name in ("semanage.trans.LOCK", "semanage.read.LOCK"):
        for path in (root / "etc/selinux").glob(f"*/{name}"):
            path.unlink()

    (root / "usr/lib/sysimage/rpm/.rpm.lock").unlink(missing_ok=True)

    (root / "var/cache/ldconfig/aux-cache").unlink(missing_ok=True)


def path_identity(root, path):
    path = resolve_in_root(root, path, follow_final=False)
    try:
        parent = path.parent.stat()
    except (FileNotFoundError, NotADirectoryError):
        return None
    return parent.st_dev, parent.st_ino, path.name


def existing_tmpfiles(root):
    # Configuration with the same basename is overridden as a whole; the
    # effective files are then processed in filename order by systemd.
    configs = {}
    for directory in (
        "etc/tmpfiles.d",
        "run/tmpfiles.d",
        "usr/local/lib/tmpfiles.d",
        "usr/lib/tmpfiles.d",
    ):
        directory_path = resolve_in_root(root, directory)
        for path in sorted(directory_path.glob("*.conf")):
            configs.setdefault(path.name, path)

    covered = {}
    specifiers = {
        "%": "%",
        "S": "/var/lib",
        "C": "/var/cache",
        "L": "/var/log",
        "t": "/run",
        "T": "/tmp",
        "V": "/var/tmp",
    }
    for name, path in sorted(configs.items()):
        if name == AUTOVAR:
            continue
        path = resolve_in_root(root, path.relative_to(root))
        # /dev/null masks and dangling configuration symlinks contain no rules.
        if not path.is_file():
            continue
        for number, line in enumerate(
            path.read_text(errors="surrogateescape").splitlines(), 1
        ):
            if not line.strip() or line.lstrip().startswith(("#", ";")):
                continue
            try:
                kind, declared = tmpfiles_fields(line)
                if kind[0] not in "fFdDvqQpLcCb":
                    continue  # Attribute and cleanup rules do not create paths.
                try:
                    declared = re.sub(r"%(.|$)", lambda m: specifiers[m[1]], declared)
                except KeyError:
                    continue  # Machine-specific paths cannot be resolved here.
                identity = path_identity(root, declared)
                if identity is not None:
                    covered.setdefault(identity, kind[0])
            except (ValueError, OSError) as error:
                raise ValueError(f"{path}:{number}: {error}") from error
    return covered


def account_names(root, database):
    names = {}
    for line in (root / "etc" / database).read_text().splitlines():
        name, _, identity, *_ = line.split(":")
        names.setdefault(int(identity), name)
    return names


def var_tmpfiles(root):
    """Describe missing /var directories and links without deleting state."""
    covered = existing_tmpfiles(root)
    users = account_names(root, "passwd")
    groups = account_names(root, "group")
    entries = []
    var = resolve_in_root(root, "var")

    def walk(directory):
        parent = directory.stat()
        for path in sorted(directory.iterdir()):
            metadata = path.lstat()
            identity = parent.st_dev, parent.st_ino, path.name
            image_path = "/" + path.relative_to(root).as_posix()
            if identity not in covered:
                if stat.S_ISDIR(metadata.st_mode):
                    user = users.get(metadata.st_uid, str(metadata.st_uid))
                    group = groups.get(metadata.st_gid, str(metadata.st_gid))
                    entries.append(
                        f"d {tmpfiles_escape(image_path)} {stat.S_IMODE(metadata.st_mode):04o} "
                        f"{tmpfiles_escape(user)} {tmpfiles_escape(group)} - -"
                    )
                elif stat.S_ISLNK(metadata.st_mode):
                    entries.append(
                        f"L {tmpfiles_escape(image_path)} - - - - {tmpfiles_escape(os.readlink(path))}"
                    )
            # C rules initialize an entire subtree from a factory copy.
            if stat.S_ISDIR(metadata.st_mode) and covered.get(identity) != "C":
                walk(path)

    walk(var)
    return sorted(entries)


def write_var_tmpfiles(root):
    output = resolve_in_root(root, f"usr/lib/tmpfiles.d/{AUTOVAR}", follow_final=False)
    entries = var_tmpfiles(root)
    qm_root = resolve_in_root(root, "usr/lib/qm/rootfs")
    if qm_root.is_dir():
        entries, qm_entries = split_qm_tmpfiles(entries)
        qm_output = resolve_in_root(root, QM_VAR_TMPFILES, follow_final=False)
        qm_output.parent.mkdir(parents=True, exist_ok=True)
        ensure_file_contents(
            qm_output,
            AUTOVAR_HEADER + "".join(f"{entry}\n" for entry in qm_entries),
            0o644,
        )
    contents = AUTOVAR_HEADER + "".join(f"{entry}\n" for entry in entries)
    ensure_file_contents(output, contents, 0o644)


def relocate_directory(root, source, destination):
    """Move a directory without losing its metadata or replacing destination data."""
    source = resolve_in_root(root, source, follow_final=False)
    destination = resolve_in_root(root, destination, follow_final=False)
    if source.is_symlink():
        return
    # rename preserves metadata and fails if the destination contains data.
    source.rename(destination)
    source.symlink_to(os.path.relpath(destination, source.parent))


def prepare_layout(root):
    for source, destination in (
        ("root", "var/roothome"),
        ("home", "var/home"),
        ("mnt", "var/mnt"),
    ):
        relocate_directory(root, source, destination)

    media = root / "media"
    if not media.is_symlink():
        media.rmdir()
        media.symlink_to("run/media")

    alternatives = resolve_in_root(root, "var/lib/alternatives", follow_final=False)
    if alternatives.is_dir() and not alternatives.is_symlink():
        relocate_directory(root, "var/lib/alternatives", "usr/lib/alternatives")


def set_assignment(path, key, value):
    contents = path.read_text() if path.exists() else ""
    pattern = re.compile(rf"^\s*{re.escape(key)}\s*=.*$", re.MULTILINE)
    line = f"{key}={value}"
    if pattern.search(contents):
        contents = pattern.sub(line, contents)
    else:
        contents = contents.rstrip("\n") + "\n" + line + "\n"
    ensure_file_contents(path, contents, 0o644)


def selinux_policy(root):
    config = resolve_in_root(root, "etc/selinux/config")
    settings = {}
    for line in config.read_text().splitlines():
        key, separator, value = line.partition("=")
        if separator and not key.lstrip().startswith("#"):
            settings[key.strip()] = value.split("#", 1)[0].strip().strip("\"'")
    if settings.get("SELINUX") == "disabled":
        return None
    return settings["SELINUXTYPE"]


def prepare_selinux_aliases(root, policy):
    path = resolve_in_root(
        root, f"etc/selinux/{policy}/contexts/files/file_contexts.subs_dist"
    )
    lines = path.read_text().splitlines() if path.exists() else []
    aliases = {"/home": "/var/home", "/var/lib/selinux": "/etc/selinux"}
    result = []
    for line in lines:
        fields = line.split("#", 1)[0].split()
        if fields and fields[0] in aliases:
            continue  # Replace our aliases rather than adding duplicate entries.
        if fields and fields[0] == "/var/home":
            # Do not leave a reverse mapping that would form an alias loop.
            result.append("# Disabled by composefs_postprocess: " + line)
        else:
            result.append(line)
    result.extend(f"{source} {target}" for source, target in aliases.items())
    ensure_file_contents(path, "\n".join(result) + "\n", 0o644)


def relocate_selinux_store(root, policy):
    source = resolve_in_root(root, "var/lib/selinux", follow_final=False)
    if source.is_symlink():
        return
    if not (source / policy / "active/modules").is_dir():
        return
    destination = resolve_in_root(root, "etc/selinux")

    # Move the module store alongside existing policy without replacing files.
    def merge(src, dst):
        for child in src.iterdir():
            target = dst / child.name
            if (
                child.is_dir()
                and not child.is_symlink()
                and target.is_dir()
                and not target.is_symlink()
            ):
                merge(child, target)
            else:
                if target.exists() or target.is_symlink():
                    raise FileExistsError(
                        f"SELinux store destination already contains data: {target}"
                    )
                child.rename(target)
        src.rmdir()

    merge(source, destination)
    source.symlink_to("../../etc/selinux")
    set_assignment(
        resolve_in_root(root, "etc/selinux/semanage.conf"), "store-root", "/etc/selinux"
    )


def normalize_shadow(root):
    path = resolve_in_root(root, "etc/shadow")
    lines = []
    for line in path.read_text().splitlines():
        fields = line.split(":")
        if fields[1].startswith(("!", "*")):
            fields[2] = ""
        lines.append(":".join(fields))
    ensure_file_contents(path, "\n".join(lines) + "\n")


def run_in_root(root, commands):
    # Reuse osbuild's mount and chroot setup, and execute tools from the image.
    from osbuild.util.chroot import Chroot

    with Chroot(str(root)) as chroot:
        for command in commands:
            chroot.run(command, check=True)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("root", type=Path)
    args = parser.parse_args()

    root = args.root.resolve()
    boot = root / "boot"

    prepare_layout(root)
    set_assignment(resolve_in_root(root, "etc/default/useradd"), "HOME", "/var/home")
    commands = []
    policy = selinux_policy(root)
    if policy:
        prepare_selinux_aliases(root, policy)
        commands.extend([["semodule", "-nB"], ["semodule", "-n", "--refresh"]])
    modules = resolve_in_root(root, "usr/lib/modules")
    for kernel in sorted(modules.iterdir()):
        commands.append(["depmod", "-a", kernel.name])
        hmac = kernel / ".vmlinuz.hmac"
        if hmac.is_file() and "/" in hmac.read_text():
            digest, filename = hmac.read_text().split("  ", 1)
            ensure_file_contents(
                hmac, digest + "  " + Path(filename.strip()).name + "\n", 0o644
            )
    if commands:
        run_in_root(root, commands)
    if policy:
        relocate_selinux_store(root, policy)
    normalize_shadow(root)
    cleanup(root)
    write_var_tmpfiles(root)

    for pattern in ("vmlinuz-*", "symvers-*", "System.map-*", "config-*"):
        for path in boot.glob(pattern):
            path.unlink()

    for path in (boot / "loader", boot / "grub2", *boot.glob("dtb-*")):
        if path.is_dir() and not path.is_symlink():
            shutil.rmtree(path)
        else:
            path.unlink(missing_ok=True)


if __name__ == "__main__":
    main()
