#!/usr/bin/python3
"""Windows components (OpenAL, d3dx, XAudio, ...) for a game's Proton prefix.

The app installs each component under STORE/<id>: its files in system32/ (64-bit) and syswow64/
(32-bit) as Windows lays them out, and component.json naming the overrides that make Wine load
them instead of its own ("name" for native-then-builtin, or "name=n" with Wine's own letters) and
the components it bundles ("requires"). The ids are Bannerlator's catalog names (xaudio2.7,
oalinst_dll...). The user picks components per game; the picks are in SELECTION as
{"version": 1, "games": {"<appid>": ["oalinst_dll", ...]}}.

droiddeck-game-env calls apply() before every game launch. It copies what is missing or changed
into compatdata/<appid>/pfx and returns the overrides for WINEDLLOVERRIDES, so nothing is written
to the prefix's registry and Wine never has to be running.

Proton leaves the files alone afterwards: its builtin refresh (update_builtin_libs) replaces only
files that are its own builtins, and a new prefix is built around files already there (copy_pfx
skips them). The one case that removes them is a launch on an older Proton than the prefix's,
which deletes every file Proton once placed - and the next launch's apply() puts ours back.
"""
import json
import os
import re
import shutil
import sys
from pathlib import Path

STORE = Path("/opt/droiddeck/wincomponents")
SELECTION = Path.home() / ".config/droiddeck/wincomponents.json"
# What this prefix holds from us, so a component the user turns off is taken out again.
STATE = ".droiddeck-wincomponents.json"
# A file ours replaced that was not Proton's (a real installer's, the user's own), put back when the
# component is turned off. Proton's builtins need no copy: it restores those itself.
BACKUP = ".droiddeck-wincomponents-backup"
BUILTIN_MARKS = (b"Wine builtin DLL", b"Wine placeholder DLL")
ARCH_DIRS = ("system32", "syswow64")
ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,63}")


def valid_id(value):
    return isinstance(value, str) and ID.fullmatch(value) is not None and ".." not in value


def wanted(app_id, selection=SELECTION):
    try:
        with open(selection, encoding="utf-8") as source:
            config = json.load(source)
    except FileNotFoundError:
        return []
    if config.get("version") != 1:
        raise ValueError("unsupported components selection")
    ids = config.get("games", {}).get(app_id, [])
    if not isinstance(ids, list) or not all(valid_id(i) for i in ids):
        raise ValueError("invalid components selection")
    return ids


def component(store, cid):
    """The component's overrides, its files as (relative path, source) and the ids it bundles, or None if not installed."""
    root = Path(store) / cid
    try:
        with open(root / "component.json", encoding="utf-8") as source:
            meta = json.load(source)
    except (FileNotFoundError, ValueError):
        return None
    files = []
    for arch in ARCH_DIRS:
        folder = root / arch
        if folder.is_dir():
            # A few go one level down (gmdls: system32/drivers/gm.dls).
            for entry in sorted(folder.rglob("*")):
                if entry.is_file() and not entry.is_symlink():
                    rel = entry.relative_to(folder).as_posix().lower()
                    files.append(("drive_c/windows/%s/%s" % (arch, rel), entry))
    requires = [r for r in meta.get("requires", []) if valid_id(r)]
    return [str(o) for o in meta.get("overrides", [])], files, requires


def expand(store, ids):
    """The picks with everything they bundle, each once, a bundle's parts before it."""
    out, seen = [], set()

    def visit(cid, depth):
        if cid in seen or depth > 8:
            return
        seen.add(cid)
        found = component(store, cid)
        for dep in (found[2] if found else []):
            visit(dep, depth + 1)
        out.append(cid)

    for cid in ids:
        visit(cid, 0)
    return out


def existing(path):
    """The file at path as the prefix spells it: Windows names ignore case, the filesystem may not."""
    folder = path.parent
    try:
        with os.scandir(folder) as entries:
            for entry in entries:
                if entry.name.lower() == path.name:
                    return folder / entry.name
    except OSError:
        pass
    return None


def same(src, dst):
    try:
        if dst.is_symlink():
            return False
        a, b = src.stat(), dst.stat()
    except OSError:
        return False
    return a.st_size == b.st_size and int(a.st_mtime) == int(b.st_mtime)


def builtin(path):
    """Proton's own: a symlink into its files, or a Wine DLL that says so in its DOS stub."""
    if path.is_symlink():
        return True
    try:
        with open(path, "rb") as source:
            head = source.read(512)
    except OSError:
        return False
    return any(mark in head for mark in BUILTIN_MARKS)


def place(src, target, backup=None):
    """Copies src over target unless it is already there; a file of someone else's goes to backup first."""
    target.parent.mkdir(parents=True, exist_ok=True)
    found = existing(target)
    if found is not None and same(src, found):
        return False
    if found is not None and backup is not None and not backup.exists() and not builtin(found):
        backup.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(found, backup)
    final = found or target
    temp = final.with_name(".%s.droiddeck" % final.name)
    shutil.copy2(src, temp)
    # Over a Proton builtin this swaps its symlink for our file.
    os.replace(temp, final)
    return True


def load_state(compat):
    try:
        with open(compat / STATE, encoding="utf-8") as source:
            state = json.load(source)
        return state if isinstance(state.get("files"), dict) else {"files": {}}
    except (FileNotFoundError, ValueError, AttributeError):
        return {"files": {}}


def save_state(compat, state):
    temp = compat / (STATE + ".tmp")
    with open(temp, "w", encoding="utf-8") as out:
        json.dump(state, out, indent=1, sort_keys=True)
    os.replace(temp, compat / STATE)


def apply(compat_path, app_id, selection=SELECTION, store=STORE):
    """Brings the prefix in line with the game's picks. Returns (overrides, notes)."""
    compat = Path(compat_path)
    pfx = compat / "pfx"
    ids = wanted(app_id, selection)
    state = load_state(compat)
    if not ids and not state["files"]:
        return [], []
    notes, overrides, keep = [], [], {}
    copied = 0
    installed = []
    for cid in expand(store, ids):
        found = component(store, cid)
        if found is None:
            notes.append("%s is not installed; skipped" % cid)
            continue
        installed.append(cid)
        names, files, _ = found
        overrides += names
        for rel, src in files:
            # A file this prefix already has from us is ours to replace; anything else is kept.
            if place(src, pfx / rel, None if rel in state["files"] else compat / BACKUP / rel):
                copied += 1
            keep[rel] = cid
    removed = restored = 0
    for rel, cid in state["files"].items():
        if rel in keep:
            continue
        path = existing(pfx / rel)
        saved = compat / BACKUP / rel
        if saved.is_file():
            target = path or (pfx / rel)
            os.replace(saved, target)
            restored += 1
        elif path is not None and not path.is_symlink():
            path.unlink()
            removed += 1
    if removed:
        # Proton refreshes its builtins only when its config changes; forgetting the config puts
        # its own DLLs back where ours were on the next launch - this one.
        try:
            (compat / "config_info").unlink()
        except FileNotFoundError:
            pass
    compat.mkdir(parents=True, exist_ok=True)
    save_state(compat, {"files": keep, "components": installed})
    if copied or removed or restored:
        note = "components %s: %d file(s) placed, %d removed" % (",".join(ids) or "none", copied, removed)
        notes.append(note + (", %d put back as they were" % restored if restored else ""))
    return overrides, notes


def overrides_value(names):
    """WINEDLLOVERRIDES entries: native-then-builtin unless the component says otherwise; the last word on a DLL wins."""
    modes = {}
    for entry in names:
        name, _, mode = entry.partition("=")
        name = name.strip().lower()
        if name and re.fullmatch(r"[a-z0-9._-]+", name) and re.fullmatch(r"[nb,]*", mode):
            modes.pop(name, None)
            modes[name] = mode if "=" in entry else "n,b"
    return ";".join("%s=%s" % item for item in modes.items())


def main():
    # droiddeck-wincomponents <compatdata dir> <appid>: what a launch would do, for a shell.
    if len(sys.argv) != 3:
        print("usage: droiddeck-wincomponents <compatdata dir> <appid>", file=sys.stderr)
        return 2
    names, notes = apply(sys.argv[1], sys.argv[2])
    for note in notes:
        print(note)
    print("WINEDLLOVERRIDES=" + overrides_value(names))
    return 0


if __name__ == "__main__":
    sys.exit(main())
