#!/usr/bin/env python3
"""FreezeOS IceWatch — the control panel for endpoint protection.

Opened from Settings → System → IceWatch, from the tray shield, or on its own.
  freezeos-icewatch [--page status|alerts|connections|programs|scan|exceptions|rules] [--socket-id=N]

The panel holds NO security logic. It reads from the IceWatch service over its
local socket and asks for every change through `pkexec icewatch …`, so the
service decides what is allowed and a change always needs the password. A
setting the fleet has locked is shown with a padlock and cannot be changed
here. Plan: docs/plans/icewatch.md.
"""

from __future__ import annotations

import json
import os
import socket
import subprocess
import sys
import threading
import time

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk, Pango  # noqa: E402

SOCKET = "/run/icewatch/icewatch.sock"
# Where the command lives: a distribution package, FreezeOS, or the from-memory copy.
CLI = next((p for p in ("/usr/bin/icewatch", "/usr/local/bin/icewatch", "/run/icewatch-preview/icewatch")
            if os.path.exists(p)), "/usr/local/bin/icewatch")
LEVELS = [("watch", "Watch", "Report only. Nothing is ever blocked."),
          ("balanced", "Balanced", "Also refuses known malware before it can start. Everything else runs as usual."),
          ("strict", "Strict", "Also: programs with no known origin may not start from temporary folders or removable media."),
          ("lockdown", "Lockdown", "Only the system, packaged software and programs on your exception list may start. For kiosks and servers.")]
READY_LEVELS = ("watch", "balanced", "strict", "lockdown")
KINDS = [("exe", "A program or a folder of programs"), ("path", "A file or folder that is changed"),
         ("rule", "A whole rule"), ("hash", "A file by its SHA-256"), ("cmdline", "A command line containing…")]
PORT_NAMES = {443: "Secure web", 80: "Web", 22: "Remote login (SSH)", 53: "Name lookup (DNS)", 853: "Name lookup (DNS)",
              25: "E-mail", 465: "E-mail", 587: "E-mail", 993: "E-mail", 143: "E-mail", 123: "Clock",
              5222: "Chat", 5228: "Google services", 3478: "Calls", 1194: "VPN", 51820: "VPN", 6667: "IRC chat",
              6697: "IRC chat", 3333: "Mining pool", 4444: "Mining pool", 8080: "Web (alternate)", 8443: "Secure web (alternate)",
              21: "File transfer", 3389: "Remote desktop", 5900: "Remote desktop", 9418: "Git", 11434: "AI server"}


def _country_names():
    """Country code -> name, from the list the time-zone data ships with
    (present on every FreezeOS image). Without it the two-letter code is shown."""
    names = {}
    for path in ("/usr/share/zoneinfo/iso3166.tab", "/usr/share/zoneinfo/posix/iso3166.tab"):
        try:
            with open(path, encoding="utf-8") as f:
                for line in f:
                    if line.startswith("#") or "\t" not in line:
                        continue
                    cc, name = line.rstrip("\n").split("\t", 1)
                    names[cc] = name
            break
        except OSError:
            continue
    # Shorter, more familiar forms where the file is formal.
    names.update({"GB": "United Kingdom", "KR": "South Korea", "KP": "North Korea", "CZ": "Czechia",
                  "US": "United States"} if names else {})
    return names


COUNTRIES = _country_names()
CSS = b"""
.iw-state { font-size: 22px; font-weight: bold; }
.iw-ok { color: #00ff88; } .iw-warn { color: #ffcc00; } .iw-bad { color: #ff4455; } .iw-dim { opacity: 0.6; }
.iw-pill { border: 1px solid alpha(currentColor, 0.5); border-radius: 9px; padding: 0 8px; font-size: 11px; }
.iw-mono { font-family: monospace; font-size: 12px; }
.iw-row { padding: 8px 4px; border-bottom: 1px solid alpha(currentColor, 0.12); }
"""


def _fz_socket_id():
    for a in sys.argv[1:]:
        if a.startswith("--socket-id="):
            try:
                return int(a.split("=", 1)[1])
            except ValueError:
                return 0
    return 0


def _fz_plug(win, socket_id):
    plug = Gtk.Plug.new(socket_id)
    child = win.get_child()
    if child is not None:
        win.remove(child)
        plug.add(child)
    win.hide()
    plug.connect("destroy", Gtk.main_quit)
    plug.show_all()
    return plug


def ask(req: dict):
    """One request to the service. None when it is not running."""
    try:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        s.settimeout(5)
        s.connect(SOCKET)
        s.sendall((json.dumps(req) + "\n").encode())
        buf = b""
        while not buf.endswith(b"\n"):
            chunk = s.recv(65536)
            if not chunk:
                break
            buf += chunk
        s.close()
        return json.loads(buf.decode() or "{}")
    except (OSError, ValueError):
        return None


def ago(ts) -> str:
    try:
        d = max(0, int(time.time()) - int(ts))
    except (TypeError, ValueError):
        return ""
    if d < 60:
        return "just now"
    if d < 3600:
        return "%d min ago" % (d // 60)
    if d < 86400:
        return "%d h ago" % (d // 3600)
    return "%d d ago" % (d // 86400)


def label(text="", cls=None, wrap=False, sel=False, xalign=0.0, markup=False):
    w = Gtk.Label(xalign=xalign)
    if markup:
        w.set_markup(text)
    else:
        w.set_text(text)
    if wrap:
        w.set_line_wrap(True)
        w.set_line_wrap_mode(Pango.WrapMode.WORD_CHAR)
        w.set_max_width_chars(90)
    w.set_selectable(sel)
    for c in (cls or "").split():
        w.get_style_context().add_class(c)
    return w


class Panel:
    def __init__(self, page):
        self.win = Gtk.Window(title="IceWatch")
        self.win.set_default_size(980, 660)
        self.win.connect("destroy", Gtk.main_quit)
        prov = Gtk.CssProvider()
        prov.load_from_data(CSS)
        Gtk.StyleContext.add_provider_for_screen(self.win.get_screen(), prov,
                                                 Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
        self.status = None
        self.busy = False
        self.show_history = False
        self.show_all_programs = False
        self.group_by = "country"
        self.show_lan = False
        self.show_incoming = False
        self.scan_text = ""
        self._sig = {}

        root = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.info = Gtk.InfoBar()
        self.info.set_no_show_all(True)
        self.info_label = label(wrap=True)
        self.info.get_content_area().add(self.info_label)
        self.info.set_show_close_button(True)
        self.info.connect("response", lambda b, _r: b.hide())
        root.pack_start(self.info, False, False, 0)

        self.stack = Gtk.Stack()
        self.stack.set_transition_type(Gtk.StackTransitionType.CROSSFADE)
        sw = Gtk.StackSwitcher()
        sw.set_stack(self.stack)
        sw.set_halign(Gtk.Align.CENTER)
        sw.set_margin_top(10)
        sw.set_margin_bottom(6)
        root.pack_start(sw, False, False, 0)
        root.pack_start(self.stack, True, True, 0)
        self.pages = {}
        for pid, title in (("status", "Status"), ("alerts", "Alerts"), ("connections", "Connections"),
                           ("programs", "Running programs"),
                           ("scan", "Scan & quarantine"), ("exceptions", "Exceptions"), ("rules", "Rules")):
            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
            box.set_border_width(16)
            sc = Gtk.ScrolledWindow()
            sc.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
            sc.add(box)
            self.stack.add_titled(sc, pid, title)
            self.pages[pid] = box
        self.win.add(root)
        self.stack.connect("notify::visible-child-name", lambda *_: self.refresh())
        self.win.show_all()
        if page in self.pages:
            self.stack.set_visible_child_name(page)
        self.refresh()
        GLib.timeout_add_seconds(5, self._auto)

    # ── plumbing ──
    def _auto(self):
        if not self.busy:
            self.refresh(quiet=True)
        return True

    def say(self, text, kind=Gtk.MessageType.INFO):
        self.info_label.set_text(text)
        self.info.set_message_type(kind)
        self.info.show()
        self.info_label.show()

    def change(self, args, done_text=None):
        """Ask the service for a change, as administrator (password prompt)."""
        if self.busy:
            return
        self.busy = True

        def work():
            try:
                p = subprocess.run(["pkexec", CLI] + args, capture_output=True, text=True, timeout=180)
                out = (p.stderr or p.stdout or "").strip()
                rc = p.returncode
            except (OSError, subprocess.SubprocessError) as e:
                out, rc = str(e), 1
            GLib.idle_add(finish, rc, out)

        def finish(rc, out):
            self.busy = False
            if rc == 0:
                if done_text:
                    self.say(done_text)
            elif rc in (126, 127):
                self.say("Nothing was changed (the password prompt was closed).", Gtk.MessageType.WARNING)
            else:
                self.say(out.replace("icewatch: ", "").capitalize() or "That could not be done.",
                         Gtk.MessageType.WARNING)
            self.refresh()
            return False

        threading.Thread(target=work, daemon=True).start()

    def clear(self, box):
        for c in box.get_children():
            box.remove(c)

    def refresh(self, quiet=False):
        st = ask({"cmd": "status"})
        self.status = (st or {}).get("status") if st and st.get("ok") else None
        page = self.stack.get_visible_child_name() or "status"
        data = None
        if self.status is not None:
            if page == "alerts":
                data = ask({"cmd": "alerts", "all": self.show_history, "limit": 300})
            elif page == "connections":
                data = ask({"cmd": "connections", "limit": 3000})
            elif page == "programs":
                data = ask({"cmd": "ps", "unverified": not self.show_all_programs})
            elif page == "exceptions":
                data = ask({"cmd": "policy"})
            elif page == "scan":
                data = ask({"cmd": "quarantine"})
            elif page == "rules":
                data = ask({"cmd": "rules"})
        # Rebuild only when something changed, so the page does not jump
        # while someone is reading or typing.
        if page == "connections" and data:
            # "last seen" moves every few seconds; do not rebuild the tree for that alone.
            sig_data = [(c.get("exe"), c.get("ip"), c.get("ports"), c.get("listed")) for c in data.get("connections") or []]
            sig_status = None
        else:
            sig_data, sig_status = data, self.status
        if page == "scan":
            sig_status = [(self.status or {}).get(k) for k in ("bad_hashes", "malware_rules", "definitions")]
        sig = json.dumps([page, sig_status, sig_data, self.show_history, self.show_all_programs, self.scan_text,
                          self.group_by, self.show_lan, self.show_incoming], sort_keys=True)
        if quiet and self._sig.get(page) == sig:
            return
        if quiet and page == "exceptions" and self._sig.get(page):
            focus = self.win.get_focus()
            if isinstance(focus, Gtk.Entry) and focus.get_text():
                return
        self._sig[page] = sig
        box = self.pages[page]
        self.clear(box)
        if self.status is None:
            self.build_off(box)
        else:
            getattr(self, "build_" + page)(box, data or {})
        box.show_all()

    def locked(self, key):
        return key in ((self.status or {}).get("locked") or [])

    # ── pages ──
    def build_off(self, box):
        box.pack_start(label("IceWatch is off", "iw-state iw-dim"), False, False, 0)
        box.pack_start(label("IceWatch watches this computer for break-ins and malware: programs that start, "
                             "changes to the files that decide who gets in, and programs that try to take over "
                             "others. It reports what it finds; it does not block anything yet.", wrap=True),
                       False, False, 0)
        if not os.path.exists(CLI):
            box.pack_start(label("IceWatch is not installed on this computer.", "iw-dim"), False, False, 0)
            return
        b = Gtk.Button(label="Switch IceWatch on")
        b.get_style_context().add_class("suggested-action")
        b.set_halign(Gtk.Align.START)
        b.connect("clicked", lambda *_: self.change(["on"], "IceWatch is on."))
        box.pack_start(b, False, False, 0)

    def build_status(self, box, _data):
        st = self.status
        level = st.get("level", "watch")
        open_n = int(st.get("alerts_open") or 0)
        paused = st.get("snooze_until") and int(st["snooze_until"]) > time.time()
        if level == "off":
            head, cls = "Off", "iw-dim"
        elif paused:
            head, cls = "Paused until %s" % time.strftime("%H:%M", time.localtime(int(st["snooze_until"]))), "iw-warn"
        elif open_n:
            head, cls = "%d finding%s need%s a look" % (open_n, "" if open_n == 1 else "s", "s" if open_n == 1 else ""), "iw-warn"
        else:
            head, cls = "Protected", "iw-ok"
        box.pack_start(label(head, "iw-state " + cls), False, False, 0)
        sub = "Nothing found." if not open_n else "Latest: %s" % ((st.get("last_alert") or {}).get("title") or "")
        if level != "off" and not paused:
            box.pack_start(label(sub, wrap=True), False, False, 0)
        if open_n:
            b = Gtk.Button(label="Show the findings")
            b.set_halign(Gtk.Align.START)
            b.connect("clicked", lambda *_: self.stack.set_visible_child_name("alerts"))
            box.pack_start(b, False, False, 0)

        # Level
        fr = Gtk.Frame(label=" Protection level ")
        inner = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        inner.set_border_width(10)
        fr.add(inner)
        lock_level = self.locked("level")
        group = None
        for lid, name, desc in LEVELS:
            rb = Gtk.RadioButton.new_with_label_from_widget(group, "%s — %s" % (name, desc))
            group = group or rb
            rb.set_active(level == lid)
            rb.set_sensitive(not lock_level and lid in READY_LEVELS)
            rb.connect("toggled", lambda w, l=lid: w.get_active() and l != level and
                       self.change(["level", l], "Protection level changed."))
            inner.pack_start(rb, False, False, 0)
        if lock_level:
            inner.pack_start(label("\U0001F512 Managed by your fleet.", "iw-dim"), False, False, 0)
        box.pack_start(fr, False, False, 0)

        # Pause / off
        row = Gtk.Box(spacing=8)
        if paused:
            b = Gtk.Button(label="Resume protection now")
            b.connect("clicked", lambda *_: self.change(["snooze", "0"], "Protection resumed."))
            row.pack_start(b, False, False, 0)
        else:
            for mins, text in ((15, "Pause 15 minutes"), (60, "Pause 1 hour")):
                b = Gtk.Button(label=text)
                b.set_sensitive(not self.locked("snooze") and level != "off")
                b.connect("clicked", lambda _w, m=mins: self.change(["snooze", str(m)], "Protection is paused."))
                row.pack_start(b, False, False, 0)
        off = Gtk.Button(label="Switch IceWatch off")
        off.set_sensitive(not lock_level)
        off.connect("clicked", lambda *_: self.change(["off"], "IceWatch is off."))
        row.pack_start(off, False, False, 0)
        test = Gtk.Button(label="Send a test alert")
        test.set_tooltip_text("Raises a harmless alert so you can see that alerts arrive")
        test.connect("clicked", lambda *_: self.change(["test"], "A test alert was raised."))
        row.pack_end(test, False, False, 0)
        box.pack_start(row, False, False, 0)
        if self.locked("snooze") and not paused:
            box.pack_start(label("\U0001F512 Pausing is not allowed by your fleet.", "iw-dim"), False, False, 0)

        # Facts
        stats = st.get("stats") or {}
        missing = [k for k, v in (st.get("sensors") or {}).items() if v is False]
        facts = [
            "Watching %s running programs; %s started since IceWatch began %s." %
            (st.get("processes", 0), stats.get("execs", 0), ago(st.get("since"))),
            "%s rules, %s exception%s." % (st.get("rules", 0), st.get("exceptions", 0),
                                          "" if st.get("exceptions") == 1 else "s"),
        ]
        if missing:
            facts.append("This computer does not offer these sensors: %s. The rest work normally." % ", ".join(missing))
        if st.get("blocking"):
            facts.append("Known malware is refused before it can start.")
        if st.get("sensors", {}).get("gate") is False and level == "balanced":
            facts.append("Blocking is not active on this computer right now; detection continues.")
        if st.get("bad_hashes"):
            facts.append("%s known-malware fingerprints, %s botnet networks%s."
                         % ("{:,}".format(st["bad_hashes"]), "{:,}".format(st.get("bad_addresses") or 0),
                            ", malware rules" if st.get("malware_rules") else ""))
        facts.append("IceWatch %s." % st.get("version", ""))
        for f in facts:
            box.pack_start(label(f, "iw-dim", wrap=True), False, False, 0)

    def build_alerts(self, box, data):
        top = Gtk.Box(spacing=8)
        cb = Gtk.CheckButton(label="Show the full history (closed and low-importance entries too)")
        cb.set_active(self.show_history)
        cb.connect("toggled", lambda w: (setattr(self, "show_history", w.get_active()), self.refresh()))
        top.pack_start(cb, False, False, 0)
        box.pack_start(top, False, False, 0)
        alerts = data.get("alerts") or []
        if not alerts:
            box.pack_start(label("No open alerts." if not self.show_history else "Nothing recorded yet.", "iw-dim"),
                           False, False, 0)
            return
        for a in alerts:
            sev = a.get("severity", "low")
            row = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=4)
            row.get_style_context().add_class("iw-row")
            head = Gtk.Box(spacing=8)
            head.pack_start(label(sev, "iw-pill " + {"high": "iw-bad", "medium": "iw-warn"}.get(sev, "iw-dim")),
                            False, False, 0)
            n = int(a.get("count") or 1)
            head.pack_start(label(a.get("title", "") + (" (×%d)" % n if n > 1 else ""), wrap=True), True, True, 0)
            state = a.get("state", "open")
            head.pack_end(label(ago(a.get("last_ts")) + ("" if state == "open" else
                                                         " · " + ("false alarm" if state == "wrong" else "closed")),
                                "iw-dim"), False, False, 0)
            row.pack_start(head, False, False, 0)
            what = a.get("exe") or a.get("path") or ""
            if what:
                row.pack_start(label(what, "iw-mono", wrap=True, sel=True), False, False, 0)
            exp = Gtk.Expander(label="Details")
            det = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
            det.set_margin_start(14)
            for name, key in (("Command", "cmdline"), ("File", "path"), ("User", "user"), ("From", "origin"),
                              ("Detail", "detail"), ("SHA-256", "sha256"), ("Rule", "rule")):
                if a.get(key) and not (key == "path" and not a.get("exe")):
                    det.pack_start(label("%s: %s" % (name, a[key]), "iw-mono", wrap=True, sel=True), False, False, 0)
            if a.get("chain"):
                det.pack_start(label("Started by: " + " → ".join(a["chain"]), "iw-mono", wrap=True), False, False, 0)
            if a.get("what_next"):
                det.pack_start(label(a["what_next"], wrap=True), False, False, 0)
            exp.add(det)
            row.pack_start(exp, False, False, 0)
            if state == "open":
                btns = Gtk.Box(spacing=8)
                d = Gtk.Button(label="Close")
                d.set_tooltip_text("You have seen it and dealt with it")
                d.connect("clicked", lambda _w, i=a["id"]: self.change(["dismiss", i]))
                w = Gtk.Button(label="This was wrong")
                w.set_tooltip_text("A false alarm: close it and add the narrowest exception so it does not come back")
                w.connect("clicked", lambda _w, i=a["id"]: self.change(["wrong", i], "Closed, and an exception was added."))
                w.set_sensitive(not self.locked("exceptions"))
                btns.pack_start(d, False, False, 0)
                btns.pack_start(w, False, False, 0)
                row.pack_start(btns, False, False, 0)
            box.pack_start(row, False, False, 0)

    def build_connections(self, box, data):
        conns = data.get("connections") or []
        top = Gtk.Box(spacing=8)
        top.pack_start(label("Group by"), False, False, 0)
        combo = Gtk.ComboBoxText()
        for gid, text in (("country", "Country"), ("program", "Program"), ("badge", "Where the program comes from"),
                          ("user", "User"), ("port", "Service (port)")):
            combo.append(gid, text)
        combo.set_active_id(self.group_by)
        combo.connect("changed", lambda w: (setattr(self, "group_by", w.get_active_id()), self.refresh()))
        top.pack_start(combo, False, False, 0)
        cb = Gtk.CheckButton(label="Include the local network")
        cb.set_active(self.show_lan)
        cb.connect("toggled", lambda w: (setattr(self, "show_lan", w.get_active()), self.refresh()))
        top.pack_start(cb, False, False, 0)
        cb2 = Gtk.CheckButton(label="Include incoming (others connecting to this computer)")
        cb2.set_active(self.show_incoming)
        cb2.connect("toggled", lambda w: (setattr(self, "show_incoming", w.get_active()), self.refresh()))
        top.pack_start(cb2, False, False, 0)
        box.pack_start(top, False, False, 0)

        notes = []
        if not data.get("country_data"):
            notes.append("Country information has not arrived from the fleet yet; addresses are shown without a country.")
        if not data.get("bad_addresses"):
            notes.append("The list of known botnet addresses has not arrived from the fleet yet.")
        else:
            notes.append("Every address is checked against %s known botnet and criminal networks."
                         % "{:,}".format(data["bad_addresses"]))
        notes.append("Shows the outside addresses each program is connected to, from the last 24 hours. "
                     "Lookups happen on this computer; nothing is sent anywhere to find a country.")
        for n in notes:
            box.pack_start(label(n, "iw-dim", wrap=True), False, False, 0)

        if not self.show_lan:
            conns = [c for c in conns if c.get("country") != "LAN"]
        if not self.show_incoming:
            conns = [c for c in conns if c.get("dir") != "in"]
        if not conns:
            box.pack_start(label("No outside connections seen yet.", "iw-dim"), False, False, 0)
            return

        def country_name(c):
            cc = c.get("country") or ""
            if cc == "LAN":
                return "Local network"
            return COUNTRIES.get(cc, cc) if cc else "Unknown country"

        def prog_name(c):
            return (c.get("exe") or "?").replace(" (deleted)", "").rsplit("/", 1)[-1]

        def service(c):
            ports = c.get("ports") or []
            p = ports[0] if ports else 0
            return "%s (port %d)" % (PORT_NAMES[p], p) if p in PORT_NAMES else "Port %d" % p

        key = {"country": country_name, "program": lambda c: c.get("exe") or "?",
               "badge": lambda c: c.get("badge") or "Unknown", "user": lambda c: c.get("user") or "?",
               "port": service}[self.group_by]
        groups = {}
        for c in conns:
            groups.setdefault(key(c), []).append(c)

        # group, program, address, country, ports, user, badge, last seen, weight, colour
        store = Gtk.TreeStore(str, str, str, str, str, str, str, str, int, str)
        order = sorted(groups.items(), key=lambda kv: (-sum(1 for c in kv[1] if c.get("listed")), -len(kv[1]), kv[0]))
        for name, rows in order:
            bad = sum(1 for c in rows if c.get("listed"))
            progs = len({c.get("exe") for c in rows})
            summary = "%d address%s, %d program%s" % (len(rows), "" if len(rows) == 1 else "es",
                                                      progs, "" if progs == 1 else "s")
            if bad:
                summary += " — %d on a botnet list" % bad
            parent = store.append(None, [name, summary, "", "", "", "", "", "", 700, "#ff4455" if bad else None])
            for c in sorted(rows, key=lambda c: (not c.get("listed"), -int(c.get("last") or 0))):
                flag = "  ⚠ on the list: %s" % c["listed"] if c.get("listed") else ""
                arrow = "← " if c.get("dir") == "in" else ""
                store.append(parent, ["", prog_name(c), arrow + (c.get("ip") or "") + flag, country_name(c),
                                      ", ".join(str(p) for p in c.get("ports") or []), c.get("user") or "",
                                      c.get("badge") or "", ago(c.get("last")), 400,
                                      "#ff4455" if c.get("listed") else None])
        tv = Gtk.TreeView(model=store)
        tv.set_tooltip_text("Double-click a row to open or close it")
        titles = {"country": "Country", "program": "Program", "badge": "Comes from", "user": "User", "port": "Service"}
        for i, title in enumerate((titles[self.group_by], "Program", "Address", "Country", "Ports", "User",
                                   "Badge", "Last seen")):
            r = Gtk.CellRendererText()
            if i in (1, 2):
                r.set_property("ellipsize", Pango.EllipsizeMode.END)
            col = Gtk.TreeViewColumn(title, r, text=i, weight=8, foreground=9)
            col.set_resizable(True)
            if i in (1, 2):
                col.set_expand(True)
            tv.append_column(col)
        if len(order) <= 6:
            tv.expand_all()
        else:
            for i, (_n, rows) in enumerate(order):
                if any(c.get("listed") for c in rows):
                    tv.expand_row(Gtk.TreePath.new_from_indices([i]), False)
        box.pack_start(tv, True, True, 0)

    def build_programs(self, box, data):
        cb = Gtk.CheckButton(label="Show every running program (not only the ones that could not be verified)")
        cb.set_active(self.show_all_programs)
        cb.connect("toggled", lambda w: (setattr(self, "show_all_programs", w.get_active()), self.refresh()))
        box.pack_start(cb, False, False, 0)
        box.pack_start(label("FreezeOS and Trusted publisher programs match what was shipped. "
                             "\"Your own\" and \"Unknown\" are not a problem by themselves: they are simply "
                             "programs IceWatch cannot trace to a signed source.", "iw-dim", wrap=True), False, False, 0)
        procs = data.get("processes") or []
        if not procs:
            box.pack_start(label("Every running program is verified.", "iw-ok"), False, False, 0)
            return
        store = Gtk.ListStore(str, str, str, str, str)
        for p in procs:
            store.append([p.get("badge", ""), str(p.get("pid", "")), p.get("user", ""),
                          p.get("exe") or "[%s]" % p.get("comm", ""), p.get("origin", "")])
        tv = Gtk.TreeView(model=store)
        for i, title in enumerate(("Badge", "PID", "User", "Program", "Comes from")):
            r = Gtk.CellRendererText()
            if i == 3:
                r.set_property("ellipsize", Pango.EllipsizeMode.MIDDLE)
            col = Gtk.TreeViewColumn(title, r, text=i)
            col.set_resizable(True)
            col.set_sort_column_id(i)
            if i == 3:
                col.set_expand(True)
            tv.append_column(col)
        box.pack_start(tv, True, True, 0)

    def run_scan(self, path):
        """Scan a file or folder as administrator and show what was found."""
        if self.busy:
            return
        self.busy = True
        self.scan_text = "Scanning %s …" % path
        self.refresh()

        def work():
            try:
                p = subprocess.run(["pkexec", CLI, "scan", path], capture_output=True, text=True, timeout=3600)
                out, rc = (p.stdout or "") + (p.stderr or ""), p.returncode
            except (OSError, subprocess.SubprocessError) as e:
                out, rc = str(e), 1
            GLib.idle_add(done, rc, out.strip())

        def done(rc, out):
            self.busy = False
            if rc in (126, 127):
                self.scan_text = "The scan was not started (the password prompt was closed)."
            elif rc not in (0, 3):
                self.scan_text = out.replace("icewatch: ", "").capitalize() or "The scan could not be run."
            else:
                self.scan_text = "%s\n%s" % (path, out)
            self.refresh()
            return False

        threading.Thread(target=work, daemon=True).start()

    def build_scan(self, box, data):
        st = self.status or {}
        ready = st.get("bad_hashes") or st.get("malware_rules")
        if ready:
            when = st.get("definitions")
            box.pack_start(label("Checks files against %s known-malware fingerprints%s. Definitions from %s."
                                 % ("{:,}".format(st.get("bad_hashes") or 0),
                                    " and the malware rules" if st.get("malware_rules") else "",
                                    time.strftime("%b %d, %H:%M", time.localtime(when)) if when else "the fleet"),
                                 "iw-dim", wrap=True), False, False, 0)
        else:
            box.pack_start(label("The malware definitions have not arrived from the fleet yet. "
                                 "Scanning becomes available as soon as they do.", "iw-dim", wrap=True), False, False, 0)
        row = Gtk.Box(spacing=8)
        home = os.path.expanduser("~")
        for text, path in (("Scan my Downloads", os.path.join(home, "Downloads")), ("Scan my home folder", home)):
            b = Gtk.Button(label=text)
            b.set_sensitive(bool(ready) and not self.busy and os.path.isdir(path))
            b.connect("clicked", lambda _w, p=path: self.run_scan(p))
            row.pack_start(b, False, False, 0)
        pick = Gtk.Button(label="Scan a folder or file…")
        pick.set_sensitive(bool(ready) and not self.busy)

        def choose(_w):
            dlg = Gtk.FileChooserDialog(title="What to scan", parent=self.win if self.win.get_visible() else None,
                                        action=Gtk.FileChooserAction.SELECT_FOLDER)
            dlg.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "Scan", Gtk.ResponseType.OK)
            path = dlg.get_filename() if dlg.run() == Gtk.ResponseType.OK else None
            dlg.destroy()
            if path:
                self.run_scan(path)
        pick.connect("clicked", choose)
        row.pack_start(pick, False, False, 0)
        box.pack_start(row, False, False, 0)
        if self.scan_text:
            fr = Gtk.Frame(label=" Last scan ")
            fr.add(label(self.scan_text, "iw-mono", wrap=True, sel=True))
            fr.get_child().set_margin_start(10)
            fr.get_child().set_margin_top(6)
            fr.get_child().set_margin_bottom(8)
            box.pack_start(fr, False, False, 0)
            found = [ln.split("  ")[1] for ln in self.scan_text.splitlines() if ln.startswith("FOUND  ") and len(ln.split("  ")) > 1]
            for path in found[:20]:
                b = Gtk.Button(label="Quarantine %s" % path)
                b.set_halign(Gtk.Align.START)
                b.connect("clicked", lambda _w, p=path: self.change(["quarantine", p], "Quarantined."))
                box.pack_start(b, False, False, 0)

        box.pack_start(label("Quarantine", "iw-state"), False, False, 6)
        box.pack_start(label("A quarantined file is taken out of circulation, not destroyed. "
                             "Put it back if it turns out to be harmless.", "iw-dim", wrap=True), False, False, 0)
        items = data.get("items") or []
        if not items:
            box.pack_start(label("Nothing is in quarantine.", "iw-dim"), False, False, 0)
        for it in items:
            r = Gtk.Box(spacing=8)
            r.get_style_context().add_class("iw-row")
            txt = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            txt.pack_start(label(it.get("path", ""), "iw-mono", wrap=True, sel=True), False, False, 0)
            txt.pack_start(label("%s · %s" % (it.get("reason", ""), ago(it.get("when"))), "iw-dim", wrap=True), False, False, 0)
            r.pack_start(txt, True, True, 0)
            back = Gtk.Button(label="Put back")
            back.connect("clicked", lambda _w, i=it.get("id", ""): self.change(["restore", i], "The file was put back."))
            gone = Gtk.Button(label="Delete for good")
            gone.connect("clicked", lambda _w, i=it.get("id", ""): self.change(["purge", i], "Deleted."))
            for b in (back, gone):
                b.set_valign(Gtk.Align.CENTER)
                r.pack_end(b, False, False, 0)
            box.pack_start(r, False, False, 0)

    def build_exceptions(self, box, data):
        lock = self.locked("exceptions")
        box.pack_start(label("An exception tells IceWatch to stay quiet about one program, folder or rule. "
                             "System folders, /boot, login files and IceWatch's own files can never be excepted.",
                             "iw-dim", wrap=True), False, False, 0)
        excs = data.get("exceptions") or []
        if not excs:
            box.pack_start(label("No exceptions.", "iw-dim"), False, False, 0)
        for e in excs:
            row = Gtk.Box(spacing=8)
            row.get_style_context().add_class("iw-row")
            txt = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            txt.pack_start(label("%s   %s" % (e.get("kind", ""), e.get("value", "")), "iw-mono", wrap=True, sel=True),
                           False, False, 0)
            bits = ["only rule %s" % e["rule"] if e.get("rule") else "every rule",
                    "until %s" % time.strftime("%b %d %H:%M", time.localtime(e["expires"])) if e.get("expires") else "permanent"]
            if e.get("note"):
                bits.append(e["note"])
            bits.append("set by your fleet" if e.get("source") == "fleet" else "added by %s" % (e.get("added_by") or "an administrator"))
            txt.pack_start(label(" · ".join(bits), "iw-dim", wrap=True), False, False, 0)
            row.pack_start(txt, True, True, 0)
            if e.get("source") != "fleet":
                b = Gtk.Button(label="Remove")
                b.set_valign(Gtk.Align.CENTER)
                b.set_sensitive(not lock)
                b.connect("clicked", lambda _w, k=e.get("kind", ""), v=e.get("value", ""):
                          self.change(["unallow", k, v], "Exception removed."))
                row.pack_end(b, False, False, 0)
            box.pack_start(row, False, False, 0)

        fr = Gtk.Frame(label=" Add an exception ")
        grid = Gtk.Grid(column_spacing=8, row_spacing=8)
        grid.set_border_width(10)
        fr.add(grid)
        kind = Gtk.ComboBoxText()
        for k, t in KINDS:
            kind.append(k, t)
        kind.set_active(0)
        value = Gtk.Entry()
        value.set_hexpand(True)
        value.set_placeholder_text("/home/you/projects/build/   (a folder ends in /)")
        browse = Gtk.Button(label="Choose a folder…")

        def pick(_w):
            dlg = Gtk.FileChooserDialog(title="Folder to except", parent=self.win if self.win.get_visible() else None,
                                        action=Gtk.FileChooserAction.SELECT_FOLDER)
            dlg.add_buttons("Cancel", Gtk.ResponseType.CANCEL, "Choose", Gtk.ResponseType.OK)
            if dlg.run() == Gtk.ResponseType.OK and dlg.get_filename():
                value.set_text(dlg.get_filename().rstrip("/") + "/")
            dlg.destroy()
        browse.connect("clicked", pick)
        dur = Gtk.ComboBoxText()
        for h, t in (("0", "Permanent"), ("1", "For 1 hour"), ("24", "For today (24 hours)"), ("168", "For 7 days")):
            dur.append(h, t)
        dur.set_active(0)
        note = Gtk.Entry()
        note.set_placeholder_text("Why (kept in the history)")
        add = Gtk.Button(label="Add")
        add.get_style_context().add_class("suggested-action")

        def do_add(_w):
            v = value.get_text().strip()
            if not v:
                self.say("Type what to except first.", Gtk.MessageType.WARNING)
                return
            args = ["allow", kind.get_active_id(), v, "--hours", dur.get_active_id()]
            if note.get_text().strip():
                args += ["--note", note.get_text().strip()]
            self.change(args, "Exception added.")
        add.connect("clicked", do_add)
        grid.attach(kind, 0, 0, 1, 1)
        grid.attach(value, 1, 0, 1, 1)
        grid.attach(browse, 2, 0, 1, 1)
        grid.attach(dur, 0, 1, 1, 1)
        grid.attach(note, 1, 1, 1, 1)
        grid.attach(add, 2, 1, 1, 1)
        fr.set_sensitive(not lock)
        box.pack_start(fr, False, False, 0)
        if lock:
            box.pack_start(label("\U0001F512 Exceptions are managed by your fleet.", "iw-dim"), False, False, 0)

    def build_rules(self, box, data):
        lock = self.locked("rules")
        box.pack_start(label("Each rule watches for one thing. High and medium rules raise an alert; "
                             "low ones are only kept in the history.", "iw-dim", wrap=True), False, False, 0)
        for r in data.get("rules") or []:
            row = Gtk.Box(spacing=10)
            row.get_style_context().add_class("iw-row")
            sev = r.get("severity", "low")
            row.pack_start(label(sev, "iw-pill " + {"high": "iw-bad", "medium": "iw-warn"}.get(sev, "iw-dim")),
                           False, False, 0)
            row.pack_start(label(r.get("title", ""), wrap=True), True, True, 0)
            sw = Gtk.Switch()
            sw.set_valign(Gtk.Align.CENTER)
            sw.set_active(bool(r.get("enabled")))
            sw.set_sensitive(not lock)
            sw.connect("state-set", lambda _w, on, rid=r.get("id", ""): self.change(["rule", rid, "on" if on else "off"]) or False)
            row.pack_end(sw, False, False, 0)
            box.pack_start(row, False, False, 0)
        if lock:
            box.pack_start(label("\U0001F512 Rules are managed by your fleet.", "iw-dim"), False, False, 0)


def main():
    page = "status"
    args = sys.argv[1:]
    if "--page" in args and args.index("--page") + 1 < len(args):
        page = args[args.index("--page") + 1]
    panel = Panel(page)
    sid = _fz_socket_id()
    if sid:
        _fz_plug(panel.win, sid)
    Gtk.main()
    return 0


if __name__ == "__main__":
    sys.exit(main())
