#!/usr/bin/python3
# Registers the card the app installs to (bound at /mnt/bannerlator-sd) as a library folder of the
# native Steam client, so they show as installed there instead of being downloaded a second time.
#
#   bannerlator-steam-library <steam root>
#
# Ported from WinNative's gamescope runtime (GPL-3.0).
import os
import re
import sys

# The client's own library is internal storage (its steamapps/common is bound to the app's root);
# the card is the one extra library folder.
LIBRARIES = (("/mnt/bannerlator-sd", "Bannerlator (card)"),)


def register(steam_root, library, label):
    """Adds one library folder to the client's list; the client then offers it as an install
    location as well as reading the games already in it. Registered even when empty: a new user
    should be able to install straight into it."""
    steamapps = os.path.join(library, "steamapps")
    if not os.path.isdir(steamapps):
        return 0
    apps = sorted(
        int(m.group(1))
        for m in (re.fullmatch(r"appmanifest_(\d+)\.acf", n) for n in os.listdir(steamapps))
        if m
    )
    marker = os.path.join(library, "libraryfolder.vdf")
    if not os.path.isfile(marker):
        with open(marker, "w", encoding="utf-8") as f:
            f.write('"libraryfolder"\n{\n\t"contentid"\t\t"%d"\n\t"label"\t\t"%s"\n}\n'
                    % (int.from_bytes(os.urandom(8), "little"), label))
    steamapps_dir = os.path.join(steam_root, "steamapps")
    path = os.path.join(steamapps_dir, "libraryfolders.vdf")
    text = ""
    if os.path.isfile(path):
        with open(path, encoding="utf-8", errors="replace") as f:
            text = f.read()
    if re.search(r'"path"\s+"%s"' % re.escape(library), text):
        return len(apps)
    indexes = [int(i) for i in re.findall(r'^\t"(\d+)"\s*$', text, re.M)]
    if not text.strip():
        text = ('"libraryfolders"\n{\n\t"0"\n\t{\n\t\t"path"\t\t"%s"\n\t\t"label"\t\t""\n\t}\n}\n'
                % steam_root)
        indexes = [0]
    entry = ['\t"%d"' % (max(indexes) + 1), "\t{", '\t\t"path"\t\t"%s"' % library,
             '\t\t"label"\t\t"%s"' % label, '\t\t"apps"', "\t\t{"]
    entry += ['\t\t\t"%d"\t\t"0"' % app for app in apps]
    entry += ["\t\t}", "\t}"]
    closing = text.rstrip().rfind("}")
    if closing < 0:
        return len(apps)
    text = text[:closing] + "\n".join(entry) + "\n" + text[closing:]
    os.makedirs(steamapps_dir, exist_ok=True)
    with open(path, "w", encoding="utf-8") as f:
        f.write(text)
    print("bannerlator-steam-library: registered %s with %d game(s)" % (library, len(apps)))
    return len(apps)


RETIRED = ("/mnt/bannerlator",)


def forget(steam_root, library):
    """Removes a library folder earlier builds registered and this one no longer binds, so the
    client does not keep offering a location that is not there."""
    path = os.path.join(steam_root, "steamapps", "libraryfolders.vdf")
    if not os.path.isfile(path):
        return
    with open(path, encoding="utf-8", errors="replace") as f:
        lines = f.read().split("\n")
    out, block, depth = [], None, 0
    for line in lines:
        if depth == 1 and re.fullmatch(r'\t"\d+"', line):
            block = [line]
            continue
        if block is not None:
            block.append(line)
            depth += line.count("{") - line.count("}")
            if depth == 1:
                if not re.search(r'"path"\s+"%s"' % re.escape(library), "\n".join(block)):
                    out.extend(block)
                block = None
            continue
        depth += line.count("{") - line.count("}")
        out.append(line)
    text = "\n".join(out)
    if text != "\n".join(lines):
        with open(path, "w", encoding="utf-8") as f:
            f.write(text)
        print("bannerlator-steam-library: forgot %s" % library)


def main():
    steam_root = sys.argv[1]
    for library in RETIRED:
        forget(steam_root, library)
    for library, label in LIBRARIES:
        register(steam_root, library, label)


if __name__ == "__main__":
    main()
