#!/usr/bin/python3
# The app's store talks to Flatpak through this: one JSON object per line on stdout, so progress
# reaches the front end as numbers rather than a terminal's redrawn bar. Per-user installation,
# Flathub as the remote, this device's architecture.
#
#   bannerlator-flatpak install <app-id>      the app and whatever runtimes it needs
#   bannerlator-flatpak uninstall <app-id>    the app, then runtimes nothing uses any more
#   bannerlator-flatpak update [<app-id>]     one app, or everything with an update
#   bannerlator-flatpak updates               what has one (a "updates" line)
#
# Lines: {"e":"op","i":1,"n":3,"kind":"install","ref":"..."} as each step starts,
# {"e":"progress","i":1,"n":3,"percent":45,"status":"..."} while it runs,
# {"e":"error","message":"..."} and {"e":"done"} at the end. Exit status 0 on success.
import json
import os
import sys

os.environ.setdefault("FLATPAK_BWRAP", "/usr/local/bin/bannerlator-bwrap")

import gi  # noqa: E402

gi.require_version("Flatpak", "1.0")
from gi.repository import Flatpak, GLib  # noqa: E402

REMOTE = "flathub"


def emit(**kw):
    sys.stdout.write(json.dumps(kw) + "\n")
    sys.stdout.flush()


def installation():
    return Flatpak.Installation.new_user(None)


def app_ref(inst, app_id):
    """The installed ref of an app, or None."""
    for ref in inst.list_installed_refs_by_kind(Flatpak.RefKind.APP, None):
        if ref.get_name() == app_id:
            return ref
    return None


def transaction(inst):
    t = Flatpak.Transaction.new_for_installation(inst, None)
    t.set_no_interaction(True)
    state = {"i": 0, "n": 0, "error": None}

    def on_ready(tr):
        state["n"] = len(tr.get_operations())
        return True

    def on_new_operation(tr, op, progress):
        state["i"] += 1
        emit(e="op", i=state["i"], n=state["n"], kind=op.get_operation_type().value_nick, ref=op.get_ref())
        progress.set_update_frequency(500)

        def changed(p):
            emit(e="progress", i=state["i"], n=state["n"], percent=p.get_progress(), status=p.get_status() or "")
        progress.connect("changed", changed)

    def on_operation_error(tr, op, err, details):
        # A runtime extension that fails to install (a missing translation, an unneeded GL
        # driver) is not worth losing the app over; anything else ends the transaction.
        non_fatal = bool(details & Flatpak.TransactionErrorDetails.NON_FATAL)
        emit(e="warning" if non_fatal else "error", message="%s: %s" % (op.get_ref(), err.message))
        if not non_fatal:
            state["error"] = err.message
        return non_fatal

    t.connect("ready", on_ready)
    t.connect("new-operation", on_new_operation)
    t.connect("operation-error", on_operation_error)
    # A dependency found on more than one remote comes from the first (Flathub, the only one).
    t.connect("choose-remote-for-ref", lambda tr, ref, runtime_ref, remotes: 0)
    t.connect("end-of-lifed-with-rebase", lambda *a: False)
    t.connect("add-new-remote", lambda *a: False)
    return t, state


def run(t, state):
    try:
        t.run(None)
    except GLib.Error as err:
        if state["error"] is None and not err.matches(Flatpak.error_quark(), Flatpak.Error.ABORTED):
            state["error"] = err.message
    if state["error"]:
        emit(e="error", message=state["error"])
        return 1
    emit(e="done")
    return 0


def install(app_id):
    inst = installation()
    arch = Flatpak.get_default_arch()
    if app_ref(inst, app_id) is not None:
        emit(e="done", note="already installed")
        return 0
    # Flathub publishes apps on "stable"; libflatpak's default branch is "master".
    branch, last = None, None
    for candidate in ("stable", "master"):
        try:
            branch = inst.fetch_remote_ref_sync(REMOTE, Flatpak.RefKind.APP, app_id, arch, candidate, None).get_branch()
            break
        except GLib.Error as err:
            last = err
    if branch is None:
        emit(e="error", message="%s is not on Flathub for %s (%s)" % (app_id, arch, last.message if last else "no branch"))
        return 1
    t, state = transaction(inst)
    t.add_install(REMOTE, "app/%s/%s/%s" % (app_id, arch, branch), None)
    return run(t, state)


def uninstall(app_id):
    inst = installation()
    ref = app_ref(inst, app_id)
    if ref is None:
        emit(e="done", note="not installed")
        return 0
    t, state = transaction(inst)
    t.add_uninstall(ref.format_ref())
    rc = run(t, state)
    if rc == 0:
        # Runtimes only this app used; Flatpak's own `uninstall --unused`.
        try:
            unused = inst.list_unused_refs(None, None)
        except GLib.Error:
            unused = []
        if unused:
            t, state = transaction(inst)
            for r in unused:
                t.add_uninstall(r.format_ref())
            run(t, state)
    return rc


def updatable(inst):
    try:
        return inst.list_installed_refs_for_update(None)
    except GLib.Error as err:
        emit(e="error", message=err.message)
        return None


def update(app_id=None):
    inst = installation()
    refs = updatable(inst)
    if refs is None:
        return 1
    if app_id:
        refs = [r for r in refs if r.get_name() == app_id or r.get_kind() == Flatpak.RefKind.RUNTIME]
    if not refs:
        emit(e="done", note="up to date")
        return 0
    t, state = transaction(inst)
    for r in refs:
        t.add_update(r.format_ref(), None, None)
    return run(t, state)


def updates():
    refs = updatable(installation())
    if refs is None:
        return 1
    emit(e="updates", apps=sorted({r.get_name() for r in refs if r.get_kind() == Flatpak.RefKind.APP}),
         runtimes=len([r for r in refs if r.get_kind() == Flatpak.RefKind.RUNTIME]))
    return 0


def main():
    if len(sys.argv) < 2:
        sys.stderr.write(__doc__ or "usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
        return 2
    cmd, args = sys.argv[1], sys.argv[2:]
    if cmd == "install" and args:
        return install(args[0])
    if cmd == "uninstall" and args:
        return uninstall(args[0])
    if cmd == "update":
        return update(args[0] if args else None)
    if cmd == "updates":
        return updates()
    sys.stderr.write("usage: bannerlator-flatpak install|uninstall|update|updates [app-id]\n")
    return 2


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