#!/usr/bin/env python3
"""A VPN switch in BlueRune's quick settings, for NetworkManager's VPN and WireGuard
connections. The tile connects and disconnects; its menu (the chevron) chooses which
connection. While one is up, a small lock sits on the bar too.

Needs nmcli and Python's GLib bindings (python-gobject on Arch). Run it with the session;
it registers again whenever BlueRune restarts, and its items go when it exits.
See docs/extensions.md.
"""

import json
import signal

import gi

gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib  # noqa: E402

try:  # GLib 2.80 moved Unix signals to GLibUnix; older ones have only GLib's.
    gi.require_version("GLibUnix", "2.0")
    from gi.repository import GLibUnix  # noqa: E402

    signal_add = GLibUnix.signal_add
except (ValueError, ImportError):
    signal_add = GLib.unix_signal_add

SHELL = "org.bluerune.Shell1"
PATH = "/org/bluerune/Extensions"
INTERFACE = "org.bluerune.Extensions1"
ID = "vpn"
# How often NetworkManager is asked, in seconds, besides right after a switch.
EVERY = 3
VPN_TYPES = ("vpn", "wireguard")


def fields(line):
    """One line of `nmcli -t`: fields split at colons that aren't escaped."""
    out, field, escaped = [], "", False
    for char in line:
        if escaped:
            field, escaped = field + char, False
        elif char == "\\":
            escaped = True
        elif char == ":":
            out, field = out + [field], ""
        else:
            field += char
    return out + [field]


class Vpn:
    def __init__(self):
        self.bus = Gio.bus_get_sync(Gio.BusType.SESSION)
        self.registered = False
        # The connections, as (name, active), and the one the tile switches.
        self.connections = []
        self.chosen = None
        self.problem = None
        self.switching = False
        self.shown = {}
        self.bus.signal_subscribe(SHELL, INTERFACE, "Activated", PATH, None, Gio.DBusSignalFlags.NONE, self.activated)
        # Register whenever BlueRune is there: now, and after it restarts.
        Gio.bus_watch_name_on_connection(self.bus, SHELL, Gio.BusNameWatcherFlags.NONE, self.shell_appeared, self.shell_vanished)
        GLib.timeout_add_seconds(EVERY, self.ask)
        self.ask()

    # --- BlueRune -------------------------------------------------------------------------

    def call(self, method, signature, args, done=None):
        """Calls the shell without waiting: the main loop must keep running to answer its pings."""

        def finished(bus, result):
            try:
                reply = bus.call_finish(result)
            except GLib.Error as error:
                if "NotRegistered" in error.message:
                    # The shell dropped us (it restarted): start again.
                    self.registered, self.shown = False, {}
                    self.register()
                else:
                    print(f"bluerune-vpn: {method} was refused: {error.message}", flush=True)
                return
            if done:
                done(reply)

        self.bus.call(SHELL, PATH, INTERFACE, method, GLib.Variant(signature, args), None, Gio.DBusCallFlags.NONE, 5000, None, finished)

    def register(self):
        def registered(_reply):
            self.registered = True
            self.show()

        self.call("Register", "(ssu)", (ID, "VPN", 1), registered)

    def shell_appeared(self, _bus, _name, _owner):
        self.registered, self.shown = False, {}
        self.register()

    def shell_vanished(self, _bus, _name):
        self.registered, self.shown = False, {}

    def update(self, slot, content):
        """Sends `content` for `slot` if it is new; `None` empties the slot."""
        if not self.registered or self.shown.get(slot) == content:
            return
        self.shown[slot] = content
        if content is None:
            self.call("Remove", "(ss)", (ID, slot))
        else:
            self.call("Update", "(sss)", (ID, slot, json.dumps(content)))

    def show(self):
        active = next((name for name, up in self.connections if up), None)
        menu = [{"label": name, "action": "use:" + name, "checked": name == self.chosen} for name, _ in self.connections]
        if self.problem:
            tile = {"text": "VPN", "icon": "vpn_key_off", "state": "unavailable", "detail": self.problem}
        elif self.switching:
            tile = {"text": "VPN", "icon": "vpn_key", "state": "busy", "detail": self.chosen or ""}
        else:
            tile = {"text": "VPN", "icon": "vpn_key", "hue": "green", "state": "on" if active else "off", "detail": active or self.chosen or "", "menu": menu}
        self.update("quick", tile)
        lock = {"icon": "vpn_lock", "hue": "success", "tooltip": f"Connected to {active}", "label": f"VPN, connected to {active}", "menu": menu} if active else None
        self.update("bar", lock)

    def activated(self, _bus, _sender, _path, _iface, _signal, args):
        ident, _slot, action, value = args.unpack()
        if ident != ID:
            return
        if action == "toggle":
            active = next((name for name, up in self.connections if up), None)
            if value == "off" and active:
                self.switch(("down", active))
            elif value == "on" and self.chosen:
                self.switch(("up", self.chosen))
            else:
                # Nothing to do: say so, so the tile stops waiting.
                self.shown.pop("quick", None)
                self.show()
        elif action == "menu" and value.startswith("use:"):
            name = value[len("use:"):]
            active = next((up_name for up_name, up in self.connections if up), None)
            self.chosen = name
            if active and active != name:
                # NetworkManager keeps one VPN up while another comes up: take it down first.
                self.switch(("down", active), ("up", name))
            self.show()
        elif action == "activate":
            # A press on the bar's lock opens quick settings, where the switch is.
            Gio.Subprocess.new(["bluerunectl", "quick", "open"], Gio.SubprocessFlags.STDOUT_SILENCE | Gio.SubprocessFlags.STDERR_SILENCE)

    # --- NetworkManager ---------------------------------------------------------------------

    def nmcli(self, args, done):
        """Runs nmcli without waiting for it; `done` gets what it printed, or None."""
        try:
            process = Gio.Subprocess.new(["nmcli", *args], Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_SILENCE)
        except GLib.Error:
            done(None)
            return

        def finished(process, result):
            try:
                _ok, out, _err = process.communicate_utf8_finish(result)
            except GLib.Error:
                out = None
            done(out if process.get_successful() else None)

        process.communicate_utf8_async(None, None, finished)

    def ask(self):
        def answered(out):
            if out is None:
                self.problem = "nmcli is not installed" if not GLib.find_program_in_path("nmcli") else "NetworkManager is not running"
                self.connections = []
            else:
                rows = [fields(line) for line in out.splitlines() if line]
                self.connections = [(row[0], row[2] == "yes") for row in rows if len(row) == 3 and row[1] in VPN_TYPES]
                self.problem = None if self.connections else "No VPN connections"
                names = [name for name, _ in self.connections]
                active = next((name for name, up in self.connections if up), None)
                if active or self.chosen not in names:
                    self.chosen = active or (names[0] if names else None)
            self.show()

        if not self.switching:
            self.nmcli(["-t", "-f", "NAME,TYPE,ACTIVE", "connection", "show"], answered)
        return GLib.SOURCE_CONTINUE

    def switch(self, *steps):
        """Runs `nmcli connection <how> id <name>` for each (how, name), one after another."""
        self.switching = True
        self.show()

        def next_step(remaining):
            if not remaining:
                self.switching = False
                self.ask()
                return
            (how, name), rest = remaining[0], remaining[1:]
            self.nmcli(["connection", how, "id", name], lambda _out: next_step(rest))

        next_step(steps)


if __name__ == "__main__":
    loop = GLib.MainLoop()
    for number in (signal.SIGTERM, signal.SIGINT):
        signal_add(GLib.PRIORITY_DEFAULT, number, loop.quit)
    Vpn()
    loop.run()
