#!/usr/bin/env python3
"""Gives a non-Steam shortcut to Updraft its library artwork and icon (packaging/deck/README.md).

    python3 steam_art.py --exe PATH --art DIR [--steam DIR] [--wait SECONDS] [--icon]

Finds the shortcuts whose program is PATH in every Steam account's `shortcuts.vdf`, and copies the pictures in DIR
(`capsule.png`, `wide.png`, `hero.png`, `logo.png`, `icon.png`) into that account's `config/grid/`, named by the
shortcut's app id as Steam expects. Steam shows them after it restarts.

With `--icon` it also points the shortcut's icon at the copied `icon.png`. That rewrites `shortcuts.vdf`, which Steam
overwrites from memory while it runs, so it is only done while Steam is closed (exit status 3 otherwise). The first
rewrite keeps the original as `shortcuts.vdf.before-updraft`.

`--wait` keeps looking for the shortcut for that long: Steam may take a moment to save one just added.
Exit status: 0 done, 1 no such shortcut, 3 the icon was skipped because Steam is running.
"""

import argparse
import os
import shutil
import struct
import sys
import time
import zlib
from pathlib import Path

# Which picture goes to which grid file name. `{}` is the shortcut's app id.
GRID_NAMES = {
    "capsule.png": "{}p.png",
    "wide.png": "{}.png",
    "hero.png": "{}_hero.png",
    "logo.png": "{}_logo.png",
    "icon.png": "{}_icon.png",
}

# Binary VDF: a type byte, a NUL-terminated key, then the value. A map ends with END.
MAP, STRING, INT32, FLOAT32, UINT64, END = 0, 1, 2, 3, 7, 8


def parse_vdf(data: bytes) -> dict:
    def cstring(i):
        j = data.index(b"\0", i)
        return data[i:j].decode("utf-8", "surrogateescape"), j + 1

    def read_map(i):
        out = {}
        while True:
            kind = data[i]
            i += 1
            if kind == END:
                return out, i
            key, i = cstring(i)
            if kind == MAP:
                value, i = read_map(i)
            elif kind == STRING:
                value, i = cstring(i)
            elif kind == INT32:
                value = (INT32, struct.unpack_from("<I", data, i)[0])
                i += 4
            elif kind == FLOAT32:
                value = (FLOAT32, data[i : i + 4])
                i += 4
            elif kind == UINT64:
                value = (UINT64, data[i : i + 8])
                i += 8
            else:
                raise ValueError(f"unknown binary VDF type {kind} at byte {i - 1}")
            out[key] = value

    root, end = read_map(0)
    if end != len(data):
        raise ValueError("trailing bytes after the binary VDF")
    return root


def write_vdf(root: dict) -> bytes:
    out = bytearray()

    def key(kind, name):
        out.append(kind)
        out.extend(name.encode("utf-8", "surrogateescape") + b"\0")

    def write_map(m):
        for name, value in m.items():
            if isinstance(value, dict):
                key(MAP, name)
                write_map(value)
            elif isinstance(value, str):
                key(STRING, name)
                out.extend(value.encode("utf-8", "surrogateescape") + b"\0")
            else:
                kind, raw = value
                key(kind, name)
                out.extend(struct.pack("<I", raw) if kind == INT32 else raw)
        out.append(END)

    write_map(root)
    return bytes(out)


def get(shortcut: dict, name: str):
    """Steam has spelled some keys in different cases over the years (`exe`, `Exe`)."""
    for key, value in shortcut.items():
        if key.lower() == name.lower():
            return key, value
    return None, None


def app_id(shortcut: dict) -> int:
    _, value = get(shortcut, "appid")
    if isinstance(value, tuple) and value[0] == INT32:
        return value[1]
    # Older shortcuts have no stored id: Steam derives it from the program and the name.
    _, exe = get(shortcut, "exe")
    _, name = get(shortcut, "appname")
    return zlib.crc32(((exe or "") + (name or "")).encode("utf-8")) | 0x80000000


def same_program(exe_field: str, exe: Path) -> bool:
    return os.path.realpath(exe_field.strip().strip('"')) == os.path.realpath(exe)


def steam_running() -> bool:
    if os.environ.get("UPDRAFT_STEAM_RUNNING") in ("0", "1"):  # for the tests
        return os.environ["UPDRAFT_STEAM_RUNNING"] == "1"
    for proc in Path("/proc").iterdir():
        if proc.name.isdigit():
            try:
                if (proc / "comm").read_text().strip() == "steam":
                    return True
            except OSError:
                pass
    return False


def matches(steam: Path, exe: Path):
    """(shortcuts.vdf path, parsed root, the matching shortcut maps) for each account that has the shortcut."""
    found = []
    for vdf in sorted(steam.glob("userdata/*/config/shortcuts.vdf")):
        try:
            root = parse_vdf(vdf.read_bytes())
        except (OSError, ValueError, IndexError) as err:
            print(f"steam_art: skipping {vdf}: {err}", file=sys.stderr)
            continue
        _, shortcuts = get(root, "shortcuts")
        hits = [s for s in (shortcuts or {}).values() if isinstance(s, dict) and same_program(get(s, "exe")[1] or "", exe)]
        if hits:
            found.append((vdf, root, hits))
    return found


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--exe", required=True, type=Path)
    parser.add_argument("--art", required=True, type=Path)
    parser.add_argument("--steam", type=Path, default=Path.home() / ".local/share/Steam")
    parser.add_argument("--wait", type=float, default=0)
    parser.add_argument("--icon", action="store_true")
    args = parser.parse_args(argv)

    deadline = time.monotonic() + args.wait
    while not (found := matches(args.steam, args.exe)) and time.monotonic() < deadline:
        time.sleep(1)
    if not found:
        print(f"steam_art: no Steam shortcut runs {args.exe}", file=sys.stderr)
        return 1

    status = 0
    for vdf, root, hits in found:
        grid = vdf.parent / "grid"
        grid.mkdir(exist_ok=True)
        changed = False
        for shortcut in hits:
            appid = app_id(shortcut)
            for picture, pattern in GRID_NAMES.items():
                if (args.art / picture).is_file():
                    shutil.copyfile(args.art / picture, grid / pattern.format(appid))
            print(f"steam_art: artwork for app {appid} in {grid}")
            icon = str(grid / GRID_NAMES["icon.png"].format(appid))
            key, current = get(shortcut, "icon")
            if args.icon and (args.art / "icon.png").is_file() and current != icon:
                shortcut[key or "icon"] = icon
                changed = True
        if not changed:
            continue
        if steam_running():
            print("steam_art: Steam is running, so the icon is left for now (close Steam and run this again)", file=sys.stderr)
            status = 3
            continue
        backup = vdf.with_name("shortcuts.vdf.before-updraft")
        if not backup.exists():
            shutil.copy2(vdf, backup)
        tmp = vdf.with_name("shortcuts.vdf.updraft-tmp")
        tmp.write_bytes(write_vdf(root))
        os.replace(tmp, vdf)
        print(f"steam_art: icon set in {vdf}")
    return status


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