#!/usr/bin/env python3
"""Minimal pinentry adapter used by Lumen for in-launcher vault unlock.

rbw spawns this program with a pinentry command stream on stdin. When
PINENTRY_USER_DATA starts with ``lumen-socket:`` the password is read from the
one-shot Unix socket named after that prefix. Anything else is handed to the
system pinentry, so terminal and TUI use keeps working unchanged.
"""

from __future__ import annotations

import os
import socket
import sys

_CANCEL = "ERR 83886179 cancelled\n"
_PREFIX = "lumen-socket:"


def percent_encode(data: bytes) -> str:
    """Encode a password for the pinentry ``D`` response line."""

    encoded: list[str] = []
    for byte in data:
        if byte == 0x25 or byte < 0x20 or byte > 0x7E:
            encoded.append(f"%{byte:02x}")
        else:
            encoded.append(chr(byte))
    return "".join(encoded)


def fetch_password(marker: str) -> bytes | None:
    if not marker.startswith(_PREFIX):
        return None
    path = marker[len(_PREFIX) :]
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as client:
            client.settimeout(10)
            client.connect(path)
            chunks: list[bytes] = []
            while True:
                chunk = client.recv(4096)
                if not chunk:
                    break
                chunks.append(chunk)
            return b"".join(chunks)
    except OSError:
        return None


def main() -> int:
    marker = os.environ.get("PINENTRY_USER_DATA", "")
    if not marker.startswith("lumen-"):
        os.execvp("pinentry", ["pinentry", *sys.argv[1:]])

    for line in sys.stdin:
        command = line.strip().split(maxsplit=1)[0] if line.strip() else ""
        if command == "GETPIN":
            password = fetch_password(marker)
            if password is None:
                sys.stdout.write(_CANCEL)
                sys.stdout.flush()
                return 1
            sys.stdout.write(f"D {percent_encode(password)}\nOK\n")
            sys.stdout.flush()
            return 0
        sys.stdout.write("OK\n")
        sys.stdout.flush()
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
