#!/usr/bin/env python3
"""Prepare the tracked VoidLibrary sources consumed by VLS's native VBS recipe."""

import argparse
from contextlib import ExitStack, contextmanager
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import tempfile


UPSTREAM = "https://git.faumaray.com/Void/VoidLibrary.git"
PROJECT = Path(__file__).resolve().parents[1]

# The VBS recipe's module closure, including the Crypto and Text foundations.
MODULES = ("Async", "Configuration", "Core", "Crypto", "Data", "Functional", "LogState",
           "Math", "System", "Testing", "Text", "Time", "Unicode")
SOURCE_DIRS = {f"src/{module}" for module in MODULES}
PUBLIC_DIRS = {f"include/Void/{module}" for module in MODULES if module != "LogState"}
SUPPORT = {"include/Void/Detail/Enum.hpp", "include/Void/Log/Log.hpp", "include/Void/Stacktrace/Color.hpp"}
# These co-located public headers belong to optional modules outside the closure.
OPTIONAL = {
    "include/Void/Configuration/ReloadController.hpp", "include/Void/Crypto/AsyncHash.hpp",
    "include/Void/System/AsyncProcess.hpp", "include/Void/System/AsyncWatcher.hpp",
}
REQUIRED = SUPPORT | {
    "include/Void/Configuration/Argparse.hpp", "include/Void/Core/Hash.hpp",
    "include/Void/Crypto/Crypto.hpp", "include/Void/Data/StrictJson.hpp",
    "include/Void/System/Process.hpp", "include/Void/Testing/Test.hpp",
    "include/Void/Text/Url.hpp", "include/Void/Unicode/Utf.hpp",
    "src/Configuration/Argparse.cpp", "src/Crypto/Crypto.cpp", "src/LogState/State.cpp",
    "src/System/Process.cpp", "src/Testing/Main.cpp",
}
SCOPES = sorted({"build.cpp"} | SOURCE_DIRS | PUBLIC_DIRS | SUPPORT)
PRIVATE_NAMES = {"keys", "secrets", "credentials"}
DIRECTORY = os.O_DIRECTORY | os.O_NOFOLLOW | os.O_RDONLY


class PreparationError(Exception):
    pass


def git(repo, *args):
    # Plumbing reads raw objects/index entries. Never check out or run a dependency's
    # filters, fsmonitor, hooks, submodule commands or lazy object fetches.
    env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
    env.update(GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1", GIT_NO_LAZY_FETCH="1",
               GIT_NO_REPLACE_OBJECTS="1", GIT_OPTIONAL_LOCKS="0",
               GIT_ALLOW_PROTOCOL="https" if args[0] == "fetch" else "",
               GIT_TERMINAL_PROMPT="0")
    cmd = ["git", "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
           "-c", "credential.helper=", "-C", str(repo), *args]
    result = subprocess.run(cmd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                            stderr=subprocess.DEVNULL)
    if result.returncode:
        raise PreparationError(f"git {args[0]} failed (exit {result.returncode})")
    return result.stdout


def selected(path):
    if path in SUPPORT:
        return True
    parent, _, name = path.rpartition("/")
    if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*\.(cpp|h|hh|hpp|hxx|ipp|inl|tpp)", name)
            or name.partition(".")[0].lower() in PRIVATE_NAMES):
        return False
    parts = parent.split("/")
    if any(not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_-]*", part)
           or part.lower() in PRIVATE_NAMES for part in parts):
        return False
    # VBS recursively collects translation units under each selected module.
    return ("/".join(parts[:2]) in SOURCE_DIRS or
            ("/".join(parts[:3]) in PUBLIC_DIRS and not name.endswith(".cpp") and path not in OPTIONAL))


def inventory(repo, revision=None):
    if revision:
        rows = git(repo, "ls-tree", "-rz", revision, "--", *SCOPES)
    else:
        rows = git(repo, "ls-files", "--stage", "-z", "--", *SCOPES)
    blobs = {}
    for row in rows.split(b"\0"):
        if not row:
            continue
        fields, name = row.split(b"\t", 1)
        path = os.fsdecode(name)
        if path == "build.cpp" or path.startswith("build.cpp/"):
            raise PreparationError("tracked root build.cpp requires recipe review")
        if not selected(path):
            if path.endswith(".cpp") and "/".join(path.split("/")[:2]) in SOURCE_DIRS:
                raise PreparationError("unsupported tracked translation unit in a recipe source directory")
            continue
        mode, second, third = fields.split()
        if mode not in (b"100644", b"100755") or (not revision and third != b"0"):
            raise PreparationError("selected Git input is a link, special file or unmerged entry")
        blobs[path] = (mode, (third if revision else second).decode("ascii"))
    return blobs


def commit(repo, ref):
    value = git(repo, "rev-parse", "--verify", ref + "^{commit}").strip().decode("ascii")
    if not re.fullmatch(r"(?:[0-9a-f]{40}|[0-9a-f]{64})", value):
        raise PreparationError("invalid Git revision")
    return value


@contextmanager
def directory(path, parent=None):
    fd = os.open(path, DIRECTORY, dir_fd=parent)
    try:
        yield fd
    finally:
        os.close(fd)


def local_file(root, path):
    # Pin every directory component and refuse links on every open, including the
    # leaf. O_NONBLOCK keeps a substituted FIFO from hanging before fstat.
    with ExitStack() as stack:
        parts = path.split("/")
        for part in parts[:-1]:
            root = stack.enter_context(directory(part, root))
        fd = os.open(parts[-1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=root)
        with os.fdopen(fd, "rb") as stream:
            info = os.fstat(fd)
            if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
                raise PreparationError("local input must be a regular, singly linked file")
            stamp = (info.st_dev, info.st_ino, info.st_size, info.st_ctime_ns, info.st_mtime_ns)
            mode = b"100755" if info.st_mode & stat.S_IXUSR else b"100644"
            return stream.read(), stamp, mode


def materialize(work, tree, source):
    local = source is not None
    if local:
        repo = Path(source).resolve(strict=True)
        top = os.fsdecode(git(repo, "rev-parse", "--show-toplevel").removesuffix(b"\n"))
        if Path(top) != repo:
            raise PreparationError("--source must name the root of a Git working tree")
        ref = "HEAD"
    else:
        repo = work / "upstream.git"
        git(work, "init", "--bare", "--template=", str(repo))
        git(repo, "fetch", "--no-tags", "--no-recurse-submodules", "--no-auto-maintenance",
            "--depth=1", UPSTREAM, "refs/heads/main")
        ref = "FETCH_HEAD"

    revision = commit(repo, ref)
    committed = inventory(repo, revision)
    inputs = inventory(repo) if local else committed
    if not REQUIRED.issubset(inputs) or not PUBLIC_DIRS.issubset({p.rpartition("/")[0] for p in inputs}):
        raise PreparationError("incomplete VoidLibrary recipe inputs for the required modules")
    dirty = inputs != committed
    digest = hashlib.sha256()
    captured = {}
    with ExitStack() as stack:
        root = stack.enter_context(directory(repo)) if local else None
        for path, (mode, oid) in sorted(inputs.items()):
            if local:
                data, stamp, file_mode = local_file(root, path)
                algorithm = "sha1" if len(oid) == 40 else "sha256"
                blob = hashlib.new(algorithm, f"blob {len(data)}\0".encode())
                blob.update(data)
                dirty |= file_mode != mode or blob.hexdigest() != oid
            else:
                data = git(repo, "cat-file", "blob", oid)
            target = tree / path
            target.parent.mkdir(parents=True, exist_ok=True)
            target.write_bytes(data)
            content_hash = hashlib.sha256(data).digest()
            digest.update(path.encode("ascii") + b"\0" + content_hash)
            if local:
                captured[path] = (stamp, content_hash)
        if local:
            # All captured files existed together between these two passes. A rename,
            # write, symlink substitution or tracking change invalidates the capture.
            for path, expected in captured.items():
                data, stamp, _ = local_file(root, path)
                if (stamp, hashlib.sha256(data).digest()) != expected:
                    raise PreparationError("local sources changed during preparation; retry")
            if (not os.path.samestat(os.fstat(root), repo.stat()) or commit(repo, ref) != revision
                    or inventory(repo) != inputs):
                raise PreparationError("local Git checkout changed during preparation; retry")
    (tree / "src/Core").mkdir(parents=True, exist_ok=True)  # VBS recipe detection; Core is header-only.
    provenance = {"format": 1, "source_kind": "local" if local else "main", "revision": revision,
                  "dirty": dirty, "content_sha256": digest.hexdigest()}
    if local:
        try:
            provenance["source_path"] = os.fsencode(repo).decode("utf-8")
        except UnicodeDecodeError:
            raise PreparationError("local source path must be valid UTF-8") from None
    else:
        provenance["source_url"] = UPSTREAM
    metadata = (json.dumps(provenance, sort_keys=True) + "\n").encode("utf-8")
    if len(metadata) > 32768:
        raise PreparationError("provenance exceeds 32 KiB")
    (tree / "provenance.json").write_bytes(metadata)
    return hashlib.sha256(metadata).hexdigest()


def check_existing(tree, target):
    # Only read expected regular files in the tool's store. Reject any extra
    # entry (especially a descriptor) before selecting an existing generation.
    for base, dirs, files in os.walk(tree):
        peer = target / Path(base).relative_to(tree)
        info = peer.lstat()
        if (info.st_uid != os.geteuid() or info.st_mode != (stat.S_IFDIR | 0o555)
                or set(os.listdir(peer)) != set(dirs + files)):
            raise PreparationError("existing generation has unexpected entries or permissions")
        for name in files:
            src, dst = Path(base) / name, peer / name
            info = dst.lstat()
            if (info.st_uid != os.geteuid() or info.st_nlink != 1 or info.st_mode != (stat.S_IFREG | 0o444)
                    or info.st_size != src.stat().st_size
                    or src.read_bytes() != dst.read_bytes()):
                raise PreparationError("existing generation has unexpected file contents or permissions")


def prepare(source):
    build = PROJECT / "build"
    store = build / "voidlibrary"
    sources = store / "sources"
    for path in (build, store, sources):
        path.mkdir(mode=0o700, exist_ok=True)
        info = path.lstat()
        if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o022:
            raise PreparationError(f"expected an owned directory protected from other writers: {path}")
    # Stage beside the final directory. Renaming a sealed directory across parents
    # can require write access to its ".." entry.
    with (tempfile.TemporaryDirectory(dir=store, prefix=".prepare-") as temp,
          tempfile.TemporaryDirectory(dir=sources, prefix=".stage-") as stage):
        work, tree = Path(temp), Path(stage)
        key = materialize(work, tree, source)
        target = sources / key
        with directory(store) as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            current = store / "current"
            if os.path.lexists(current) and (not current.is_symlink() or
                    not re.fullmatch(r"sources/[0-9a-f]{64}", os.readlink(current))):
                raise PreparationError("current is outside the preparation tool's managed layout")
            if os.path.lexists(target):
                check_existing(tree, target)
            else:
                for base, _, files in os.walk(tree, topdown=False):
                    for name in files:
                        (Path(base) / name).chmod(0o444)
                    Path(base).chmod(0o555)
                tree.rename(target)
            link = work / "current"
            link.symlink_to(Path("sources") / key)
            link.replace(current)
    return target


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__,
        epilog="Defaults to the official refs/heads/main. Prints the immutable source directory "
               "and atomically points build/voidlibrary/current at it. Local dirty status covers "
               "the selected tracked build inputs.",
    )
    parser.add_argument("--source", default=os.environ.get("VLS_VOID_SOURCE_DIR") or None,
                        metavar="CHECKOUT", help="development checkout (also VLS_VOID_SOURCE_DIR)")
    try:
        print(prepare(parser.parse_args().source))
    except (PreparationError, OSError) as exc:
        sys.exit("prepare-voidlibrary: " + (exc.strerror if isinstance(exc, OSError) else str(exc)))
