#!/usr/bin/python3 -I
"""User-side pinentry and udiskie integration; no PIN in argv, env, or files."""

import fcntl
import json
import os
from pathlib import Path
import shlex
import shutil
import subprocess
import sys
from urllib.parse import unquote_to_bytes

ROOT_HELPER = "/usr/local/libexec/yubikey-usb"


def pinentry_secret(response):
    lines = response.splitlines()
    if any(line.startswith(b"ERR ") for line in lines):
        return None
    secret = b"".join(
        unquote_to_bytes(line[2:]) for line in lines if line.startswith(b"D ")
    )
    if not secret or any(byte < 32 or byte == 127 for byte in secret):
        return None
    return secret


def ask_pinentry(description, prompt):
    commands = (
        f"SETTITLE USB unlock\nSETDESC {description}\n"
        f"SETPROMPT {prompt}\nGETPIN\nBYE\n"
    ).encode()
    result = subprocess.run(
        ["@PINENTRY@", "--timeout", "120"], input=commands,
        stdout=subprocess.PIPE, check=True,
    )
    return pinentry_secret(result.stdout)


def notify(message):
    print(f"YubiKey USB: {message}", file=sys.stderr)
    if shutil.which("notify-send"):
        subprocess.run(
            ["notify-send", "YubiKey USB", message],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False,
        )


def probe_device(device):
    result = subprocess.run(
        ["@PKEXEC@", "--disable-internal-agent", ROOT_HELPER, "probe", device],
        stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, check=False,
    )
    if result.returncode == 3:
        return None
    if result.returncode:
        raise RuntimeError("USB validation failed or was not authorized. Check installation and group membership.")
    return json.loads(result.stdout)


def open_usb(device, info=None):
    runtime = os.environ.get("XDG_RUNTIME_DIR")
    if not runtime:
        raise RuntimeError("Run from your graphical login session (XDG_RUNTIME_DIR is missing).")
    if info is None:
        info = probe_device(device)
    if info is None:
        notify("Expected a non-system USB LUKS2 device with an enrolled FIDO2 token.")
        return 3
    with (Path(runtime) / f"yubikey-usb-{info['uuid']}.lock").open("a") as lock:
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return 1
        if info["unlocked"]:
            return 0
        tokens = subprocess.run(
            ["@FIDO2_TOKEN@", "-L"], stdout=subprocess.PIPE, check=True,
        )
        if not tokens.stdout.strip():
            notify("Insert your YubiKey, then retry.")
            return 1
        pin = ask_pinentry(
            "Enter your FIDO2 PIN. Then touch your YubiKey when it flashes.",
            "YubiKey PIN:",
        )
        if pin is None:
            return 1
        result = subprocess.run(
            ["@PKEXEC@", "--disable-internal-agent", ROOT_HELPER, "open", info["device"]],
            input=pin + b"\n", stdout=sys.stderr, check=False,
        )
        del pin
        if result.returncode:
            notify("Unlock failed. Check the key, PIN, and installation. No automatic retry.")
        return result.returncode


def prompt_device(device):
    info = probe_device(device)
    if info is not None:
        open_usb(device, info)
        # Never return the FIDO2 PIN as a LUKS passphrase to udiskie.
        # udiskie mounts the cleartext device when UDisks announces it.
        return 1
    if Path("/usr/bin/omarchy-drive-unlock").exists():
        os.execv("/usr/bin/omarchy-drive-unlock", ["omarchy-drive-unlock", device])
        return 1
    # Non-Omarchy machines retain a normal passphrase prompt for other drives.
    secret = ask_pinentry("Enter the LUKS passphrase for the other encrypted drive.", "Passphrase:")
    if secret is None:
        return 1
    sys.stdout.buffer.write(secret + b"\n")
    return 0


def udiskie_arguments(arguments):
    arguments = list(arguments)
    prompt = shlex.join([str(Path.home() / ".local/bin/yubikey-usb"), "prompt", "{device_file}"])
    for index in range(1, len(arguments)):
        if (arguments[index - 1] in ("--password-prompt", "-p")
                and arguments[index] == "omarchy-drive-unlock {device_file}"):
            arguments[index] = prompt
    return arguments


def main(arguments):
    if arguments and arguments[0] == "--udiskie":
        os.execv("/usr/bin/udiskie", ["udiskie", *udiskie_arguments(arguments[1:])])
        return 1
    try:
        if len(arguments) == 2 and arguments[0] == "open":
            return open_usb(arguments[1])
        if len(arguments) == 2 and arguments[0] == "close":
            return subprocess.run(
                ["@PKEXEC@", "--disable-internal-agent", ROOT_HELPER, "close", arguments[1]],
                stdin=subprocess.DEVNULL, check=False,
            ).returncode
        if len(arguments) == 2 and arguments[0] == "prompt":
            return prompt_device(arguments[1])
        print("Usage: yubikey-usb {open|close|prompt} DEVICE", file=sys.stderr)
        return 2
    except (OSError, ValueError, KeyError, subprocess.SubprocessError, RuntimeError) as error:
        notify(str(error))
        return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
