#!/usr/bin/env python3
"""A card on BlueRune's desktop with the processor's use over the last minute, as a figure
and a line, and how full memory and swap are.

Reads /proc every two seconds; needs nothing but Python's GLib bindings (python-gobject on
Arch). Run it with the session; it registers again whenever BlueRune restarts, and its card
goes when it exits. A press on the card opens the system monitor. See docs/extensions.md.
"""

import json
import signal
import subprocess

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 = "system"
# The revision that brought desktop cards.
PROTOCOL = 2
# How often /proc is read, in seconds, and how many readings the line shows: a minute.
EVERY = 2
KEPT = 30
# What a press on the card opens, the first that is installed.
MONITORS = ("bluerune-monitor", "gnome-system-monitor", "plasma-systemmonitor")


def processor():
    """The time the processors have spent busy and in all, from /proc/stat."""
    with open("/proc/stat") as stat:
        values = [int(value) for value in stat.readline().split()[1:]]
    idle = values[3] + (values[4] if len(values) > 4 else 0)
    return sum(values) - idle, sum(values)


def memory():
    """Memory and swap as (used, total) in KiB, from /proc/meminfo."""
    info = {}
    with open("/proc/meminfo") as meminfo:
        for line in meminfo:
            name, value = line.split(":", 1)
            info[name] = int(value.split()[0])
    mem = (info["MemTotal"] - info.get("MemAvailable", info["MemFree"]), info["MemTotal"])
    swap = (info.get("SwapTotal", 0) - info.get("SwapFree", 0), info.get("SwapTotal", 0))
    return mem, swap


def gigabytes(kib):
    return f"{kib / 1024 / 1024:.1f}"


class System:
    def __init__(self):
        self.bus = Gio.bus_get_sync(Gio.BusType.SESSION)
        self.registered = False
        self.shown = None
        self.readings = []
        self.last = processor()
        self.bus.signal_subscribe(SHELL, INTERFACE, "Activated", PATH, None, Gio.DBusSignalFlags.NONE, self.activated)
        Gio.bus_watch_name_on_connection(self.bus, SHELL, Gio.BusNameWatcherFlags.NONE, self.shell_appeared, self.shell_vanished)
        GLib.timeout_add_seconds(EVERY, self.read)

    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:
                    self.registered, self.shown = False, None
                    self.register()
                else:
                    print(f"bluerune-system: {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):
            (revision,) = reply.unpack()
            if revision < PROTOCOL:
                print("bluerune-system: this BlueRune has no desktop cards", flush=True)
                return
            self.registered = True
            self.show()

        self.call("Register", "(ssu)", (ID, "System", PROTOCOL), registered)

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

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

    def read(self):
        busy, total = processor()
        last_busy, last_total = self.last
        self.last = (busy, total)
        if total > last_total:
            self.readings = (self.readings + [100 * (busy - last_busy) / (total - last_total)])[-KEPT:]
        self.show()
        return GLib.SOURCE_CONTINUE

    def show(self):
        if not self.registered or not self.readings:
            return
        (used, total), (swapped, swap) = memory()
        now = round(self.readings[-1])
        rows = [{"text": "Memory", "detail": f"{gigabytes(used)} of {gigabytes(total)} GB", "icon": "memory", "progress": used / total}]
        if swap:
            rows.append({"text": "Swap", "detail": f"{gigabytes(swapped)} of {gigabytes(swap)} GB", "icon": "swap_horiz", "progress": swapped / swap})
        card = {
            "icon": "monitoring",
            "hue": "warning" if now >= 90 else "purple",
            "text": f"{now}%",
            "detail": "Processor, the last minute",
            "chart": [round(value, 1) for value in self.readings],
            "list": rows,
            "label": f"Processor at {now}%, memory {round(100 * used / total)}% full",
        }
        if card != self.shown:
            self.shown = card
            self.call("Update", "(sss)", (ID, "desktop", json.dumps(card)))

    def activated(self, _bus, _sender, _path, _interface, _signal, args):
        ident, slot, action, _value = args.unpack()
        if ident != ID or slot != "desktop" or action != "activate":
            return
        for program in MONITORS:
            if GLib.find_program_in_path(program):
                subprocess.Popen([program], start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                return


def main():
    loop = GLib.MainLoop()
    System()
    for number in (signal.SIGINT, signal.SIGTERM):
        signal_add(GLib.PRIORITY_DEFAULT, number, loop.quit)
    loop.run()


if __name__ == "__main__":
    main()
