#!/usr/bin/env python3
#
# SPDX-License-Identifier: MIT
#
# This utility clones the openrazer repository, extracts the known VID/PID combos
# for "RazerBlade" keyboards and spits out a libinput-compatible quirks file
# with those keyboards listed as "Internal".
#
# Usage:
# $ cd path/to/libinput.git/
# $ ./tools/razer-quirks-list.py

from pathlib import Path
from collections import namedtuple
import tempfile
import shutil
import subprocess
import sys


KeyboardDescriptor = namedtuple("KeyboardDescriptor", ["vid", "pid", "name"])

with tempfile.TemporaryDirectory() as tmpdir:
    # Clone the openrazer directory and add its Python modyle basedir
    # to our sys.path so we can import it
    subprocess.run(
        [
            "git",
            "clone",
            "--quiet",
            "--depth=1",
            "https://github.com/openrazer/openrazer",
        ],
        cwd=tmpdir,
        check=True,
    )
    sys.path.append(str(Path(tmpdir) / "openrazer" / "daemon"))

    import openrazer_daemon.hardware.keyboards as razer_keyboards  # type: ignore

    keyboards: list[KeyboardDescriptor] = []

    # All classnames for the keyboards we care about start with RazerBlade
    for clsname in filter(lambda c: c.startswith("RazerBlade"), dir(razer_keyboards)):
        kbd = getattr(razer_keyboards, clsname)
        try:
            k = KeyboardDescriptor(name=clsname, vid=kbd.USB_VID, pid=kbd.USB_PID)
            keyboards.append(k)
        except AttributeError:
            continue

    tmpfile = Path(tmpdir) / "30-vendor-razer.quirks"
    try:
        quirksfile = next(Path("quirks").glob("30-vendor-razer.quirks"))
    except StopIteration:
        print("Unable to find the razer quirks file.")
        raise SystemExit(1)

    with open(tmpfile, "w") as output:
        with open(quirksfile) as input:
            for line in input:
                output.write(line)
                if line.startswith("# AUTOGENERATED"):
                    output.write("\n")
                    break

        for kbd in sorted(keyboards, key=lambda k: k.vid << 16 | k.pid):
            print(
                "\n".join(
                    (
                        f"[{kbd.name} Keyboard]",
                        "MatchUdevType=keyboard",
                        "MatchBus=usb",
                        f"MatchVendor=0x{kbd.vid:04X}",
                        f"MatchProduct=0x{kbd.pid:04X}",
                        "AttrKeyboardIntegration=internal",
                    )
                ),
                file=output,
            )
            print(file=output)

    shutil.copy(tmpfile, quirksfile)
