#!/usr/bin/env python3
"""LinuxDoors Package Manager -- background download watcher. Runs as the
logged-in desktop user (NOT root -- installing still needs a root prompt;
this just notices a browser download and offers to act on it), started via
XDG autostart. Watches ~/Downloads for a file matching a known LinuxDoors
package's <name>-<version>.zip naming convention (the same filename the
website's /downloads/packages/ zips already use) and offers to install it
-- either the file that's already there, or build the same package from
real source instead. This is the actual "then a fantastic Installer will
appear" hand-off the website's Install button is supposed to trigger --
without this, clicking Install was just a relabeled Download link that
went nowhere.
"""
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gio, GLib
import json
import os
import re
import subprocess
import sys
import time
import urllib.request

# Same real gap as linuxdoors_pkg_backend.py -- this system has no
# system-wide CA trust store, so a plain urllib HTTPS call fails
# CERTIFICATE_VERIFY_FAILED. This bit us for real: _known_packages() below
# was silently failing on every run (caught by its own bare except), so
# the cache never populated and the watcher never matched ANY downloaded
# zip -- no dialog ever appeared, no error either. Confirmed live via a
# minimal Gio.FileMonitor probe (events fired correctly) plus a direct
# urllib call reproducing the exact SSLCertVerificationError.
def _ld_ca_bundle():
    # curl's Mozilla bundle first; pip's vendored certifi for any Python 3.x
    # as a fallback (a hard-coded python3.14 path broke when Python moved on).
    import glob as _g
    for _p in (["/etc/ssl/certs/ca-certificates.crt"] +
               sorted(_g.glob("/usr/lib/python3.*/site-packages/pip/_vendor/certifi/cacert.pem"),
                      key=lambda s: [int(x) if x.isdigit() else x for x in s.replace("/", ".").split(".")],
                      reverse=True)):
        if os.path.exists(_p):
            return _p
    return "/etc/ssl/certs/ca-certificates.crt"
os.environ.setdefault("SSL_CERT_FILE", _ld_ca_bundle())

API_BASE = "https://linuxdoors.com"
DOWNLOADS_DIR = os.path.expanduser("~/Downloads")
INSTALLED_DIR = "/var/lib/linuxdoors-pkg/installed"
ZIP_RE = re.compile(r"^([A-Za-z0-9][\w.+-]*)-([0-9][\w.]*)\.zip$")

_seen = set()
_packages_cache = {"at": 0, "by_name": {}}


def _known_packages():
    now = time.time()
    if now - _packages_cache["at"] > 300 or not _packages_cache["by_name"]:
        try:
            with urllib.request.urlopen(f"{API_BASE}/api/packages", timeout=15) as resp:
                data = json.loads(resp.read().decode())
            _packages_cache["by_name"] = {p["name"]: p for p in data["packages"]}
            _packages_cache["at"] = now
        except Exception as exc:
            # Don't swallow this silently -- a background watcher with no
            # window has no other way to surface "the package list never
            # loaded," and that exact silence hid a real SSL-cert bug once
            # already (see the SSL_CERT_FILE comment above).
            print(f"linuxdoors-pkg-watch: could not fetch package list: {exc}",
                  file=sys.stderr, flush=True)
    return _packages_cache["by_name"]


def _is_installed(name):
    return os.path.exists(os.path.join(INSTALLED_DIR, f"{name}.json"))


def _on_changed(_monitor, gfile, _other, event_type):
    # CHANGES_DONE_HINT (not CREATED) -- browsers write a .part file then
    # rename/finish; this is the event that actually means "the download
    # is complete," avoiding a race against a half-written zip.
    if event_type != Gio.FileMonitorEvent.CHANGES_DONE_HINT:
        return
    path = gfile.get_path()
    if not path or path in _seen:
        return
    fn = os.path.basename(path)
    m = ZIP_RE.match(fn)
    if not m:
        return
    name, version = m.group(1), m.group(2)
    pkg = _known_packages().get(name)
    if pkg is None or pkg.get("version") != version:
        return
    _seen.add(path)
    if _is_installed(name):
        return
    GLib.idle_add(_offer_install, name, version, path)


def _offer_install(name, version, zip_path):
    dialog = Gtk.MessageDialog(
        modal=True,
        message_type=Gtk.MessageType.QUESTION,
        text=f"Install {name} {version}?",
    )
    dialog.format_secondary_text(
        f"LinuxDoors detected a downloaded package: {os.path.basename(zip_path)}\n"
        "How would you like to install it?"
    )
    dialog.add_buttons(
        "Ignore", Gtk.ResponseType.CANCEL,
        "Build from source", 2,
        "Install now", Gtk.ResponseType.OK,
    )
    ok_btn = dialog.get_widget_for_response(Gtk.ResponseType.OK)
    ok_btn.get_style_context().add_class("suggested-action")
    response = dialog.run()
    dialog.destroy()

    if response == Gtk.ResponseType.OK:
        _spawn_cli_install(name, version, "precompiled-download", zip_path)
    elif response == 2:
        _spawn_cli_install(name, version, "source", None)
    return False


def _spawn_cli_install(name, version, method, zip_path):
    # Same elevation pattern as the Desktop launcher itself (su -c ... root
    # inside a terminal, prompting for the root password) -- the watcher
    # runs unprivileged the whole time, only the actual install step
    # elevates, and only after the user explicitly picks a method.
    cmd = f"/usr/local/bin/linuxdoors-pkg-manager --cli-install {name} {version} {method}"
    if zip_path:
        cmd += f" '{zip_path}'"
    subprocess.Popen([
        "xfce4-terminal", f"--title=Install {name}", "-x",
        "su", "-c", cmd, "root",
    ])


def main():
    os.makedirs(DOWNLOADS_DIR, exist_ok=True)
    gfile = Gio.File.new_for_path(DOWNLOADS_DIR)
    monitor = gfile.monitor_directory(Gio.FileMonitorFlags.NONE, None)
    monitor.connect("changed", _on_changed)
    GLib.MainLoop().run()


if __name__ == "__main__":
    main()
