#!/usr/bin/python3
"""Launch the distribution's Cheese or guvcview with the RK desktop adapter."""
import hashlib
import os
from fractions import Fraction
from pathlib import Path
import re
import subprocess
import sys
import tempfile

from modes import desktop_inventory


LIBEXEC = Path("/usr/libexec/armsom-camera-desktop")
MARKER = "# ArmSoM camera desktop override "
APPS = {"cheese", "guvcview"}


def sensor_label(entity, connector=None):
    match = re.fullmatch(r"(m\d+)_[a-z]_([^ ]+) (\d+-[\da-fA-F]+)", entity)
    if not match:
        return entity
    location = connector or f"{match[1]}, {match[3]}"
    return f"{match[2].upper()} ({location})"


def caps_string(modes):
    sizes = sorted({(m["width"], m["height"], m["fps"]["numerator"], m["fps"]["denominator"])
                    for m in modes})
    return "; ".join(f"video/x-raw,format=(string)NV12,width=(int){w},height=(int){h},"
                     f"framerate=(fraction){n}/{d}" for w, h, n, d in sizes)


def auxiliary_nodes(cameras, sys_root):
    parents = set()
    for camera in cameras:
        for entry in camera.get("auxiliary", ()):
            # Device major/minor and current sysfs name are checked again
            # by each GUI's discovery shim before this hint is applied.
            yield Path(entry["node"]).name, entry["entity"]
        for step in camera["route"]:
            node = sys_root / "class/video4linux" / Path(step["node"]).name
            media = sys_root / "class/media" / Path(step["media"]).name
            for dev in (media / "device", node / "device"):
                if dev.exists():
                    parents.add(dev.resolve())
    directory = sys_root / "class/video4linux"
    if not directory.is_dir():
        return
    for node in directory.iterdir():
        if re.fullmatch(r"(?:video|v4l-subdev)\d+", node.name) and (node / "device").resolve() in parents:
            try:
                name = (node / "name").read_text().strip()
            except OSError:
                continue
            if name != "rkisp_mainpath":
                yield node.name, name


def camera_environment(app, cameras, base, sys_root=Path("/sys"), inactive=()):
    env = base.copy()
    inventory = cameras
    cameras = [c for c in cameras if c["managed"] and c["video"]["entity"] == "rkisp_mainpath"]
    if not cameras and not inactive:
        return env
    env["ARMSOM_DESKTOP_CAMERA"] = "1"
    if app == "guvcview":
        env.setdefault("SDL_RENDER_VSYNC", "1")
    for c in cameras:
        node = Path(c["video_node"]).name
        env["ARMSOM_CAMERA_LABEL_" + node] = sensor_label(c["sensor"]["entity"], c.get("connector"))
        if app == "cheese":
            env["ARMSOM_CAMERA_CAPS_" + node] = caps_string(c["modes"])
    for node, name in auxiliary_nodes(cameras, sys_root):
        env["ARMSOM_CAMERA_HIDE_" + node] = name
    for path, name in inactive:
        node = Path(path).name
        env["ARMSOM_CAMERA_HIDE_" + node] = name
        if app == "guvcview" and name == "rkisp_mainpath":
            # Empty (present) requests libv4l's existing fail-closed behavior:
            # when its independent live topology check finds no sensor,
            # QUERYCAP fails instead of exposing the stock virtual device.
            env["ARMSOM_CAMERA_LABEL_" + node] = ""
    active_isps = {c["isp"]["media"] for c in cameras if c.get("isp")}
    for c in inventory:
        if c.get("isp", {}).get("media") in active_isps and c["video"]["entity"] == "rkisp_selfpath":
            env["ARMSOM_CAMERA_HIDE_" + Path(c["video_node"]).name] = "rkisp_selfpath"
    if app == "cheese":
        private_plugins = str(LIBEXEC / "gstreamer-1.0")
        inherited = env.get("GST_PLUGIN_PATH_1_0", env.get("GST_PLUGIN_PATH", ""))
        env["GST_PLUGIN_PATH_1_0"] = os.pathsep.join(x for x in (private_plugins, inherited) if x)
        # The vendor v4l2src caps limit applies to this process. Keep larger
        # existing limits, including on desktops with both CSI and USB cameras.
        sizes = [(m["width"], m["height"]) for c in cameras for m in c["modes"]]
        old = re.fullmatch(r"(\d+)x(\d+)", env.get("GST_V4L2SRC_MAX_RESOLUTION", ""))
        if old:
            sizes.append((int(old[1]), int(old[2])))
        if sizes:
            env["GST_V4L2SRC_MAX_RESOLUTION"] = f"{max(w for w,h in sizes)}x{max(h for w,h in sizes)}"
        # The private source already uses libv4l. GStreamer's device provider also
        # probes CIF/metadata nodes; let it use raw kernel fds to preserve libv4l slots.
        env.pop("GST_V4L2_USE_LIBV4L2", None)
        # Keep the V4L2 provider's node identity instead of a PipeWire stream.
        rank = env.get("GST_PLUGIN_FEATURE_RANK", "")
        entries = [entry for entry in rank.split(",") if entry and
                   entry.split(":")[0].strip() != "pipewiredeviceprovider"]
        env["GST_PLUGIN_FEATURE_RANK"] = ",".join(entries + ["pipewiredeviceprovider:0"])
    return env


def desktop_entry(original, app):
    section = ""
    found = False
    lines = []
    for line in original.splitlines():
        if re.fullmatch(r"\[.+\]", line):
            section = line
        if section == "[Desktop Entry]" and line.startswith("DBusActivatable="):
            line = "DBusActivatable=false"
        if (section == "[Desktop Entry]" or section.startswith("[Desktop Action ")) and line.startswith("Exec="):
            match = re.match(r'^Exec=(?:"?(?:/usr/bin/)?' + app + r'"?)(?=\s|$)(.*)$', line)
            if match:
                line = f"Exec={LIBEXEC}/desktop-launch {app}" + match[1]
                if section == "[Desktop Entry]":
                    found = True
        lines.append(line)
    if not found:
        raise ValueError(f"cannot identify the {app} Exec line")
    data = "\n".join(lines) + "\n"
    return MARKER + hashlib.sha256(data.encode()).hexdigest() + "\n" + data


def owned_entry(text):
    tag, _, body = text.partition("\n")
    return tag == MARKER + hashlib.sha256(body.encode()).hexdigest()


def update_entries(enable, destination, system=Path("/usr/share/applications"), *, system_menu=False):
    sources = [(system / "org.gnome.Cheese.desktop", "cheese")]
    if system_menu:
        sources.append((system / "guvcview.desktop", "guvcview"))
    else:
        sources += [(p, "guvcview") for p in sorted(system.glob("guvcview*.desktop"))]
    changes = []
    if enable:
        for source, app in sources:
            diverted = source.with_name(source.name + ".armsom-original")
            original = diverted if system_menu or diverted.is_file() else source
            if not original.is_file() and not system_menu:
                continue
            content = desktop_entry(original.read_text(encoding="utf-8"), app)
            target = destination / source.name
            if target.is_symlink() or (target.exists() and not owned_entry(target.read_text(encoding="utf-8"))):
                raise ValueError(f"custom desktop entry already exists: {target}")
            changes.append((target, content))
        if not changes:
            raise ValueError("no Cheese or guvcview desktop entry is installed")
        destination.mkdir(parents=True, exist_ok=True)
    else:
        targets = [destination / "org.gnome.Cheese.desktop", *sorted(destination.glob("guvcview*.desktop"))]
        for target in targets:
            if target.is_file() and not target.is_symlink():
                data = target.read_text(encoding="utf-8")
                if owned_entry(data):
                    changes.append((target, None))
                elif data.startswith(MARKER):
                    raise ValueError(f"locally edited override: {target}")
    for target, content in changes:
        if content is None:
            target.unlink()
            continue
        with tempfile.NamedTemporaryFile("w", dir=destination, delete=False,
                                         encoding="utf-8", newline="\n") as tmp:
            try:
                tmp.write(content)
                tmp.flush()
                os.chmod(tmp.name, 0o644)
            except BaseException:
                os.unlink(tmp.name)
                raise
        try:
            os.replace(tmp.name, target)
        finally:
            Path(tmp.name).unlink(missing_ok=True)


def cheese_arguments(arguments, env):
    # Cheese 43 reads only api.v4l2.path, which the plain V4L2 provider may
    # omit. Its initial device selector also accepts the exact display name.
    def mapped(value):
        if value.startswith("/dev/"):
            node = Path(os.path.realpath(value)).name
            if re.fullmatch(r"video\d+", node):
                return env.get("ARMSOM_CAMERA_LABEL_" + node, value)
        return value

    result = []
    take_device = False
    for index, value in enumerate(arguments):
        if take_device:
            result.append(mapped(value))
            take_device = False
        elif value == "--":
            return result + arguments[index:]
        elif value.startswith("--device="):
            result.append("--device=" + mapped(value.partition("=")[2]))
        elif value.startswith("-d/"):
            result.append("-d" + mapped(value[2:]))
        else:
            result.append(value)
            take_device = value in ("--device", "-d")
    return result


def guvc_arguments(arguments, cameras, inactive=()):
    if any(v in ("-d", "--device") or v.startswith(("--device=", "-d")) for v in arguments):
        return arguments
    if any(c["video_node"] == "/dev/video0" and c["reason"] == "uvc" for c in cameras):
        return arguments
    for c in cameras:
        if c["managed"] and c["video"]["entity"] == "rkisp_mainpath":
            return ["--device=" + c["video_node"], *arguments]
    if inactive:
        for c in cameras:
            if c["reason"] == "uvc" or (c["reason"] == "unsupported-sensor"
                                        and c["video"]["entity"] == "rkisp_mainpath"):
                return ["--device=" + c["video_node"], *arguments]
    return arguments


def initial_guvc_profile(modes):
    choices = [(m["width"], m["height"], Fraction(m["fps"]["numerator"], m["fps"]["denominator"]))
               for m in modes]
    full_w, full_h, _ = max(choices, key=lambda m: m[0] * m[1])
    # Prefer a native rate near 30, then the full-frame aspect ratio. This
    # selects the full-FOV binned mode on both IMX219 and OV13850.
    w, h, fps = min(choices, key=lambda m: (abs(m[2] - 30), m[0] * full_h != m[1] * full_w,
                                           -m[0] * m[1]))
    nv12 = int.from_bytes(b"NV12", "little")
    return (f"width={w}\nheight={h}\nv4l2_format={nv12}\ngui=gtk3\nrender=sdl\n"
            f"fps_num={fps.denominator}\nfps_denom={fps.numerator}\n")


def initialize_guvc_profiles(cameras, directory):
    # guvcview 2.0.8 stores settings under HOME, keyed by the device basename.
    # It re-execs itself on a device switch, so initialize every discovered
    # mainpath before handing over to the original application.
    for c in cameras:
        if (not c["managed"] or c["video"]["entity"] != "rkisp_mainpath" or not c["modes"]
                or not re.fullmatch(r"(?:m\d+_[bf]_)?(?:imx219|ov13850)\s+\S+", c["sensor"]["entity"])
                or not re.fullmatch(r"/dev/video\d+", c["video_node"])):
            continue
        path = directory / Path(c["video_node"]).name
        if os.path.lexists(path):
            continue
        directory.mkdir(parents=True, exist_ok=True)
        fd, name = tempfile.mkstemp(dir=directory)
        try:
            with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as tmp:
                tmp.write(initial_guvc_profile(c["modes"]))
            # Publish a fully written profile without replacing a concurrent
            # launcher's or guvcview's settings file.
            try:
                os.link(name, path)
            except FileExistsError:
                pass
        finally:
            os.unlink(name)


def main(args):
    if args == ["--refresh-system"]:
        update_entries(True, Path("/var/lib/armsom-camera-menus"), system_menu=True)
        return 0
    if args in (["--enable"], ["--disable"]):
        home = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local/share")
        update_entries(args == ["--enable"], home / "applications")
        return 0
    if not args or args[0] not in APPS:
        print("usage: desktop-launch {--enable|--disable|cheese [args...]|guvcview [args...]}", file=sys.stderr)
        return 2
    app = args[0]
    try:
        cameras, inactive = desktop_inventory()
    except (OSError, subprocess.SubprocessError) as exc:
        print(f"camera discovery: {exc}", file=sys.stderr)
        cameras, inactive = [], []
    env = camera_environment(app, cameras, os.environ, inactive=inactive)
    if app == "guvcview":
        try:
            initialize_guvc_profiles(cameras, Path.home() / ".config/guvcview2")
        except (OSError, RuntimeError) as exc:
            print(f"guvcview profile: {exc}", file=sys.stderr)
    binary = "/usr/bin/" + app
    argv = [binary, *(cheese_arguments(args[1:], env) if app == "cheese" else guvc_arguments(args[1:], cameras, inactive))]
    shim = LIBEXEC / ("cheese-device-name.so" if app == "cheese" else "guvc-device-filter.so")
    loader = "/lib/ld-linux-aarch64.so.1"
    if env.get("ARMSOM_DESKTOP_CAMERA") == "1" and shim.is_file():
        if app == "guvcview":
            # guvcview changes devices by spawning the basename of /proc/self/exe.
            # Run the real executable and keep the shim in its child's environment.
            inherited = [p for p in re.split(r"[:\s]+", env.get("LD_PRELOAD", ""))
                         if p and p != str(shim)]
            env["LD_PRELOAD"] = ":".join([str(shim), *inherited])
            # GSpawn resolves 'guvcview -d ...' via PATH. Keep it on this binary.
            search = env.get("PATH", os.defpath).split(":")
            env["PATH"] = ":".join(["/usr/bin", *(p for p in search if p != "/usr/bin")])
        elif Path(loader).is_file():
            argv = [loader, "--preload", str(shim), "--argv0", binary, *argv]
    os.execve(argv[0], argv, env)


if __name__ == "__main__":
    try:
        sys.exit(main(sys.argv[1:]))
    except (OSError, ValueError) as error:
        print(f"desktop-launch: {error}", file=sys.stderr)
        sys.exit(1)
