#!/usr/bin/python3 -I
# Ostiary's desktop helper for what carries no answer to ostiaryd, which asks consent
# and passphrases itself through GNOME Shell's prompter (ADR 0019). Password mode
# (--ask-password) is left for `ostiaryctl security-key enroll`, which asks the security
# key's PIN and does not link the daemon's prompter client; it prints the typed password and
# nothing when the user cancels; with --later-label, the cancel button carries that label
# and pressing it exits with LATER_EXIT_CODE, asking ostiaryd to open the prompt again
# shortly. Countdown mode (--countdown SECONDS) shows the time left in the desktop's tray
# and returns when it runs out or the user clicks the icon; without a tray it just waits.
# Tray mode (--tray) keeps an Ostiary icon in the panel and lends it to countdowns.
# Touch mode (--touch) shows a window asking to touch the security key until ostiaryd
# kills it, once the key has answered.
# Started by ostiaryd with fixed arguments; -I keeps PYTHONPATH and the user's
# site-packages out.
import argparse
import ctypes
import os
import sys
import time

# The system prompter grabs the screen; "later" lets the user fetch the password first.
LATER_EXIT_CODE = 3


PR_SET_DUMPABLE = 4


def forbid_memory_inspection() -> None:
    """No ptrace, /proc/<pid>/mem or core dump from other processes of the user.

    ostiaryd starts the prompt inside its unit's user namespace, which the user's uid
    owns: there Yama no longer keeps a dumpable process from the rest of that uid, and
    an execve made this one dumpable again whatever the daemon was.
    """
    libc = ctypes.CDLL(None, use_errno=True)
    if libc.prctl(PR_SET_DUMPABLE, 0, 0, 0, 0) != 0:
        error = ctypes.get_errno()
        raise OSError(error, os.strerror(error))


def open_prompt():
    import gi

    gi.require_version("Gcr", "4")
    from gi.repository import Gcr

    # Waits up to 60 seconds for another system prompt to close: one question at a time.
    return Gcr, Gcr.SystemPrompt.open(60, None)


def ask_password() -> int:
    parser = argparse.ArgumentParser(prog="ostiary-prompt --ask-password")
    parser.add_argument("--ask-password", action="store_true", required=True)
    parser.add_argument("--message", required=True)
    parser.add_argument("--new", action="store_true")
    parser.add_argument("--warning")
    parser.add_argument("--later-label")
    arguments = parser.parse_args()
    _, prompt = open_prompt()
    try:
        prompt.set_title("Ostiary")
        prompt.set_message(arguments.message)
        prompt.set_password_new(arguments.new)
        if arguments.warning:
            prompt.set_warning(arguments.warning)
        prompt.set_continue_label("Unlock" if not arguments.new else "Create")
        prompt.set_cancel_label(arguments.later_label or "Cancel")
        password = prompt.password(None)
        if password:
            sys.stdout.write(password + "\n")
            return 0
        # The prompter reports Escape and the cancel button alike, so both mean "later".
        return LATER_EXIT_CODE if arguments.later_label else 0
    finally:
        prompt.close()


# The StatusNotifierItem interface that GNOME's AppIndicator extension, KDE and others
# show in the panel. XAyatanaLabel is the text beside the icon.
STATUS_NOTIFIER_ITEM = """
<node>
  <interface name="org.kde.StatusNotifierItem">
    <property name="Category" type="s" access="read"/>
    <property name="Id" type="s" access="read"/>
    <property name="Title" type="s" access="read"/>
    <property name="Status" type="s" access="read"/>
    <property name="IconName" type="s" access="read"/>
    <property name="ItemIsMenu" type="b" access="read"/>
    <property name="ToolTip" type="(sa(iiay)ss)" access="read"/>
    <property name="XAyatanaLabel" type="s" access="read"/>
    <property name="Menu" type="o" access="read"/>
    <method name="Activate"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
    <method name="SecondaryActivate"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
    <method name="ContextMenu"><arg type="i" direction="in"/><arg type="i" direction="in"/></method>
    <method name="Scroll"><arg type="i" direction="in"/><arg type="s" direction="in"/></method>
    <signal name="NewToolTip"/>
    <signal name="XAyatanaNewLabel"><arg type="s"/><arg type="s"/></signal>
  </interface>
</node>
"""
# The permanent icon's own service: a countdown that returns when it runs out or the
# user clicks the icon.
TRAY_NAME = "eu.theobouge.Ostiary.Tray"
TRAY_PATH = "/eu/theobouge/Ostiary/Tray"
TRAY_INTERFACE = "eu.theobouge.Ostiary.Tray1"
TRAY_SERVICE = f"""
<node>
  <interface name="{TRAY_INTERFACE}">
    <method name="Countdown"><arg name="seconds" type="u" direction="in"/></method>
  </interface>
</node>
"""
IDLE_TOOLTIP = "Ostiary"
# GNOME's AppIndicator extension shows an item only with a menu, and on a single left
# click it opens that menu; a double click calls Activate.
DBUS_MENU = """
<node>
  <interface name="com.canonical.dbusmenu">
    <property name="Version" type="u" access="read"/>
    <property name="TextDirection" type="s" access="read"/>
    <property name="Status" type="s" access="read"/>
    <property name="IconThemePath" type="as" access="read"/>
    <method name="GetLayout">
      <arg type="i" direction="in"/><arg type="i" direction="in"/><arg type="as" direction="in"/>
      <arg type="u" direction="out"/><arg type="(ia{sv}av)" direction="out"/>
    </method>
    <method name="GetGroupProperties">
      <arg type="ai" direction="in"/><arg type="as" direction="in"/>
      <arg type="a(ia{sv})" direction="out"/>
    </method>
    <method name="GetProperty">
      <arg type="i" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="out"/>
    </method>
    <method name="Event">
      <arg type="i" direction="in"/><arg type="s" direction="in"/><arg type="v" direction="in"/>
      <arg type="u" direction="in"/>
    </method>
    <method name="EventGroup">
      <arg type="a(isvu)" direction="in"/><arg type="ai" direction="out"/>
    </method>
    <method name="AboutToShow"><arg type="i" direction="in"/><arg type="b" direction="out"/></method>
    <method name="AboutToShowGroup">
      <arg type="ai" direction="in"/><arg type="ai" direction="out"/><arg type="ai" direction="out"/>
    </method>
    <signal name="LayoutUpdated"><arg type="u"/><arg type="i"/></signal>
    <signal name="ItemsPropertiesUpdated"><arg type="a(ia{sv})"/><arg type="a(ias)"/></signal>
  </interface>
</node>
"""
MENU_PATH = "/MenuBar"
ASK_NOW_ITEM = 1


class TrayMenu:
    """One entry: "Ask again now" while a countdown runs, greyed out otherwise."""

    def __init__(self, bus, GLib, on_ask_now):
        from gi.repository import Gio

        self.bus, self.GLib, self.on_ask_now = bus, GLib, on_ask_now
        self.revision, self.waiting = 1, False
        node = Gio.DBusNodeInfo.new_for_xml(DBUS_MENU)
        bus.register_object(MENU_PATH, node.interfaces[0], self._call, self._get, None)

    def _item_properties(self, item: int) -> dict:
        Variant = self.GLib.Variant
        if item == 0:
            return {"children-display": Variant("s", "submenu")}
        label = "Ask again now" if self.waiting else "No question waiting"
        return {"label": Variant("s", label), "enabled": Variant("b", self.waiting)}

    def _layout(self):
        Variant = self.GLib.Variant
        child = Variant("(ia{sv}av)", (ASK_NOW_ITEM, self._item_properties(ASK_NOW_ITEM), []))
        return (0, self._item_properties(0), [child])

    def _call(self, connection, sender, path, interface, method, parameters, invocation):
        Variant = self.GLib.Variant
        if method == "GetLayout":
            invocation.return_value(Variant("(u(ia{sv}av))", (self.revision, self._layout())))
        elif method == "GetGroupProperties":
            ids, _ = parameters.unpack()
            found = [(item, self._item_properties(item)) for item in ids if item in (0, ASK_NOW_ITEM)]
            invocation.return_value(Variant("(a(ia{sv}))", (found,)))
        elif method == "GetProperty":
            item, name = parameters.unpack()
            invocation.return_value(Variant("(v)", (self._item_properties(item)[name],)))
        elif method in ("Event", "EventGroup"):
            events = [parameters.unpack()] if method == "Event" else parameters.unpack()[0]
            if method == "Event":
                invocation.return_value(None)
            else:
                invocation.return_value(Variant("(ai)", ([],)))
            if any(item == ASK_NOW_ITEM and event == "clicked" for item, event, *_ in events):
                self.on_ask_now()
        elif method == "AboutToShow":
            invocation.return_value(Variant("(b)", (False,)))
        elif method == "AboutToShowGroup":
            invocation.return_value(Variant("(aiai)", ([], [])))

    def _get(self, connection, sender, path, interface, name):
        Variant = self.GLib.Variant
        return {
            "Version": Variant("u", 3),
            "TextDirection": Variant("s", "ltr"),
            "Status": Variant("s", "normal"),
            "IconThemePath": Variant("as", []),
        }[name]

    def set_waiting(self, waiting: bool) -> None:
        if waiting == self.waiting:
            return
        self.waiting, self.revision = waiting, self.revision + 1
        self.bus.emit_signal(
            None, MENU_PATH, "com.canonical.dbusmenu", "LayoutUpdated",
            self.GLib.Variant("(ui)", (self.revision, 0)),
        )


class TrayIcon:
    """An Ostiary icon in the panel, with a label beside it and a tooltip."""

    def __init__(self, bus, on_activate):
        from gi.repository import Gio, GLib

        self.bus, self.GLib, self.label, self.tooltip = bus, GLib, "", IDLE_TOOLTIP
        self.menu = TrayMenu(bus, GLib, on_activate)
        node = Gio.DBusNodeInfo.new_for_xml(STATUS_NOTIFIER_ITEM)
        self.path = "/StatusNotifierItem"
        bus.register_object(self.path, node.interfaces[0], self._call(on_activate), self._get, None)
        name = f"org.kde.StatusNotifierItem-{os.getpid()}-1"
        request_name(bus, name)
        bus.call_sync(
            "org.kde.StatusNotifierWatcher", "/StatusNotifierWatcher",
            "org.kde.StatusNotifierWatcher", "RegisterStatusNotifierItem",
            GLib.Variant("(s)", (name,)), None, Gio.DBusCallFlags.NONE, -1, None,
        )

    def _call(self, on_activate):
        def on_call(connection, sender, path, interface, method, parameters, invocation):
            invocation.return_value(None)
            if method == "Activate":
                on_activate()
        return on_call

    def _get(self, connection, sender, path, interface, name):
        Variant = self.GLib.Variant
        return {
            "Category": Variant("s", "ApplicationStatus"),
            "Id": Variant("s", "ostiary"),
            "Title": Variant("s", "Ostiary"),
            "Status": Variant("s", "Active"),
            "IconName": Variant("s", "dialog-password"),
            "ItemIsMenu": Variant("b", False),
            "ToolTip": Variant("(sa(iiay)ss)", ("dialog-password", [], "Ostiary", self.tooltip)),
            "XAyatanaLabel": Variant("s", self.label),
            "Menu": Variant("o", MENU_PATH),
        }[name]

    def show(self, label: str, tooltip: str) -> None:
        self.label, self.tooltip = label, tooltip
        self.menu.set_waiting(bool(label))
        Variant = self.GLib.Variant
        emit = lambda member, values: self.bus.emit_signal(
            None, self.path, "org.kde.StatusNotifierItem", member, values
        )
        emit("XAyatanaNewLabel", Variant("(ss)", (label, "00 s")))
        emit("NewToolTip", None)


def request_name(bus, name: str) -> None:
    from gi.repository import Gio, GLib

    reply = bus.call_sync(
        "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
        "RequestName", GLib.Variant("(su)", (name, 4)), None, Gio.DBusCallFlags.NONE, -1, None,
    )
    # 1: primary owner. Anything else means another process holds the name.
    if reply.unpack()[0] != 1:
        raise RuntimeError(f"{name} is already owned")


class Countdown:
    """Counts down on an icon; finishes early when the icon is clicked."""

    def __init__(self, icon, GLib):
        self.icon, self.GLib, self.timer, self.left, self.on_done = icon, GLib, None, 0, None

    def start(self, seconds: int, on_done) -> None:
        self.finish()
        self.left, self.on_done = seconds, on_done
        if seconds <= 0:
            self.finish()
            return
        self._show()
        self.timer = self.GLib.timeout_add_seconds(1, self._tick)

    def _show(self) -> None:
        self.icon.show(
            f"{self.left} s",
            f"Ostiary asks again in {self.left} s. Double-click, or click and pick Ask again now.",
        )

    def _tick(self) -> bool:
        self.left -= 1
        if self.left <= 0:
            self.timer = None
            self.finish()
            return False
        self._show()
        return True

    def finish(self) -> None:
        if self.timer is not None:
            self.GLib.source_remove(self.timer)
            self.timer = None
        self.icon.show("", IDLE_TOOLTIP)
        on_done, self.on_done = self.on_done, None
        if on_done is not None:
            on_done()


def non_negative(text: str) -> int:
    seconds = int(text)
    if seconds < 0:
        raise ValueError(text)
    return seconds


def countdown() -> int:
    parser = argparse.ArgumentParser(prog="ostiary-prompt --countdown")
    parser.add_argument("--countdown", type=non_negative, required=True)
    seconds = parser.parse_args().countdown
    for show in (countdown_on_permanent_icon, countdown_on_own_icon):
        try:
            show(seconds)
            return 0
        except Exception:  # noqa: BLE001 - try the next way, then simply wait
            continue
    time.sleep(seconds)
    return 0


def countdown_on_permanent_icon(seconds: int) -> None:
    import gi

    gi.require_version("Gio", "2.0")
    from gi.repository import Gio, GLib

    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    bus.call_sync(
        TRAY_NAME, TRAY_PATH, TRAY_INTERFACE, "Countdown", GLib.Variant("(u)", (seconds,)),
        None, Gio.DBusCallFlags.NO_AUTO_START, (seconds + 10) * 1000, None,
    )


def countdown_on_own_icon(seconds: int) -> None:
    import gi

    gi.require_version("Gio", "2.0")
    from gi.repository import Gio, GLib

    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    loop = GLib.MainLoop()
    clock = []
    icon = TrayIcon(bus, on_activate=lambda: clock[0].finish())
    clock.append(Countdown(icon, GLib))
    clock[0].start(seconds, loop.quit)
    if seconds > 0:
        loop.run()


def tray() -> int:
    import gi

    gi.require_version("Gio", "2.0")
    from gi.repository import Gio, GLib

    bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
    clock = []
    icon = TrayIcon(bus, on_activate=lambda: clock[0].finish())
    clock.append(Countdown(icon, GLib))

    def on_call(connection, sender, path, interface, method, parameters, invocation):
        (seconds,) = parameters.unpack()
        clock[0].start(seconds, lambda: invocation.return_value(None))

    node = Gio.DBusNodeInfo.new_for_xml(TRAY_SERVICE)
    bus.register_object(TRAY_PATH, node.interfaces[0], on_call, None, None)
    request_name(bus, TRAY_NAME)
    GLib.MainLoop().run()
    return 0


def touch() -> int:
    import gi

    gi.require_version("Gtk", "4.0")
    from gi.repository import GLib, Gtk

    Gtk.init()
    window = Gtk.Window(title="Ostiary", resizable=False, default_width=360)
    box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
    for margin in ("top", "bottom", "start", "end"):
        getattr(box, f"set_margin_{margin}")(24)
    icon = Gtk.Image.new_from_icon_name("dialog-password")
    icon.set_pixel_size(64)
    title = Gtk.Label()
    title.set_markup("<big><b>Touch your security key</b></big>")
    detail = Gtk.Label(
        label="It is blinking. This window closes by itself once you touch it.",
        wrap=True,
        justify=Gtk.Justification.CENTER,
    )
    for widget in (icon, title, detail):
        box.append(widget)
    window.set_child(box)
    loop = GLib.MainLoop()
    # Closing it only hides the notice; the key still waits for its touch.
    window.connect("close-request", lambda _window: loop.quit() or False)
    window.present()
    loop.run()
    return 0


if __name__ == "__main__":
    # Consent is no longer asked here: ostiaryd speaks the prompter protocol itself and
    # checks that the answer comes from the Shell (ADR 0019). A bare invocation, which
    # used to mean the consent question, now does nothing.
    if not {"--countdown", "--tray", "--touch", "--ask-password"} & set(sys.argv[1:]):
        sys.stderr.write("ostiary-prompt: no mode given; consent is handled by ostiaryd\n")
        sys.exit(2)
    # Before any typed secret enters this process; a prompt that cannot keep it to itself
    # does not open: it gives no password.
    try:
        forbid_memory_inspection()
    except BaseException:  # noqa: BLE001 - cannot guarantee non-dumpable: hold no secret
        sys.exit(1)
    if "--countdown" in sys.argv[1:]:
        sys.exit(countdown())
    if "--tray" in sys.argv[1:]:
        try:
            code = tray()
        except BaseException:  # noqa: BLE001 - no bus or no tray: the service gives up
            code = 1
        sys.exit(code)
    if "--touch" in sys.argv[1:]:
        try:
            code = touch()
        except BaseException:  # noqa: BLE001 - no window: the key's blinking remains
            code = 1
        sys.exit(code)
    # sys.exit raises SystemExit: calling it inside the try would let the handler below
    # swallow the real exit code and turn every answer into a failure.
    try:
        code = ask_password()
    except BaseException:  # noqa: BLE001 - a failed prompt gives no password
        code = 1
    sys.exit(code)
