#!/usr/bin/python3
import json
import os
import re
import runpy
import sys

BIN_DIR = os.path.dirname(os.path.abspath(__file__))
LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("DD_LIBRARY_LABEL", "SD Card")),)
MAIN_LABEL = "Internal Storage"


def register(steam_root, library, label):
    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("droiddeck-steam-library: registered %s with %d game(s)" % (library, len(apps)))
    return len(apps)


def installdirs(libraries):
    found = set()
    for library in libraries:
        steamapps = os.path.join(library, "steamapps")
        try:
            names = os.listdir(steamapps)
        except OSError:
            continue
        for name in names:
            if not re.fullmatch(r"appmanifest_\d+\.acf", name):
                continue
            try:
                with open(os.path.join(steamapps, name), encoding="utf-8", errors="replace") as f:
                    m = re.search(r'"installdir"\s+"([^"]*)"', f.read(), re.I)
            except OSError:
                continue
            if m:
                found.add(m.group(1))
    return found


def populated(path):
    try:
        with os.scandir(path) as entries:
            return next(entries, None) is not None
    except OSError:
        return False


def adoptable(library, known):
    common = os.path.join(library, "steamapps", "common")
    try:
        names = sorted(os.listdir(common))
    except OSError:
        return []
    return [n for n in names if n not in known and not n.startswith(".")
            and os.path.isdir(os.path.join(common, n)) and populated(os.path.join(common, n))]


def adopt(steam_root, library):
    compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
    known = compat["libraries"](steam_root)
    folders = adoptable(library, installdirs(known + [library]))
    if not folders:
        return 0
    entries = compat["appinfo_entries"](os.path.join(steam_root, "appcache", "appinfo.vdf"))
    by_dir = {}
    for app, info in entries.items():
        if app not in compat["NOT_GAMES"] and info["type"] in compat["PLAYABLE_TYPES"] and info["installdir"]:
            by_dir.setdefault(info["installdir"], []).append((app, info))
    steamapps = os.path.join(library, "steamapps")
    adopted = 0
    for folder in folders:
        matches = by_dir.get(folder, [])
        games = [m for m in matches if m[1]["type"] == "game"] or matches
        if len(games) != 1:
            continue
        app, info = games[0]
        if any(os.path.isfile(os.path.join(root, "steamapps", "appmanifest_%s.acf" % app))
               for root in known + [library]):
            continue
        try:
            with open(os.path.join(steamapps, "appmanifest_%s.acf" % app), "x", encoding="utf-8") as f:
                f.write(compat["manifest_text"](app, info["name"] or folder, folder, True))
        except OSError:
            continue
        adopted += 1
        print("droiddeck-steam-library: adopted %s as app %s in %s" % (folder, app, library))
    return adopted


RETIRED = ("/mnt/bannerlator",)
RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),)


def rename(steam_root, old, new):
    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:
        text = f.read()
    old_path = re.compile(r'("path"\s+")%s(")' % re.escape(old))
    if not old_path.search(text):
        return
    if re.search(r'"path"\s+"%s"' % re.escape(new), text):
        forget(steam_root, old)
        return
    with open(path, "w", encoding="utf-8") as f:
        f.write(old_path.sub(lambda m: m.group(1) + new + m.group(2), text))
    print("droiddeck-steam-library: moved %s to %s" % (old, new))


def forget(steam_root, library):
    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("droiddeck-steam-library: forgot %s" % library)


def relabel(steam_root, target, label):
    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, depth, block, changed = [], 0, None, False
    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:
                text = "\n".join(block)
                if re.search(r'"path"\s+"%s"' % re.escape(target), text):
                    new = re.sub(r'("label"\s+")[^"]*(")', r"\g<1>%s\g<2>" % label, text, count=1)
                    if new != text:
                        changed = True
                        text = new
                out.extend(text.split("\n"))
                block = None
            continue
        depth += line.count("{") - line.count("}")
        out.append(line)
    if changed:
        with open(path, "w", encoding="utf-8") as f:
            f.write("\n".join(out))
        print("droiddeck-steam-library: labelled %s %r" % (target, label))
    marker = os.path.join(target, "libraryfolder.vdf")
    if not os.path.isfile(marker):
        return
    with open(marker, encoding="utf-8", errors="replace") as f:
        text = f.read()
    new = re.sub(r'("label"\s+")[^"]*(")', r"\g<1>%s\g<2>" % label, text, count=1)
    if new != text:
        with open(marker, "w", encoding="utf-8") as f:
            f.write(new)
        print("droiddeck-steam-library: labelled %s in its own marker too" % target)


GAMES_DIR = "/root/Games/"
ADDED_DIR = "/mnt/droiddeck-lib/"


def wanted():
    listing = os.environ.get("DD_STEAM_LIBRARIES")
    if not listing:
        return None
    try:
        with open(listing, encoding="utf-8") as f:
            entries = json.load(f)
        return [(str(e["path"]), str(e["label"]).replace('"', " ").replace("\\", " ")) for e in entries]
    except (OSError, ValueError, KeyError, TypeError):
        return None


def registered(steam_root):
    try:
        with open(os.path.join(steam_root, "steamapps", "libraryfolders.vdf"), encoding="utf-8", errors="replace") as f:
            return re.findall(r'"path"\s+"([^"]*)"', f.read())
    except OSError:
        return []


def main():
    steam_root = sys.argv[1]
    for library in RETIRED:
        forget(steam_root, library)
    for old, new in RENAMED:
        rename(steam_root, old, new)
    relabel(steam_root, steam_root, MAIN_LABEL)
    libraries = wanted()
    managed = libraries is not None
    for library, label in libraries if managed else LIBRARIES:
        if os.path.isdir(os.path.join(library, "steamapps")):
            adopt(steam_root, library)
            register(steam_root, library, label)
            relabel(steam_root, library, label)
        else:
            forget(steam_root, library)
    if managed:
        keep = {library for library, _ in libraries}
        for library in registered(steam_root):
            if library not in keep and (library == LIBRARIES[0][0] or library.startswith((GAMES_DIR, ADDED_DIR))):
                forget(steam_root, library)


if __name__ == "__main__":
    main()
