#!/usr/bin/python3
# refer to https://gitlab.freedesktop.org/-/snippets/1665
from gi.repository import GLib, Gio

FPRINT_NAMESPACE = 'net.reactivated.Fprint'
FPRINT_PATH = '/' + FPRINT_NAMESPACE.replace('.', '/')

def is_not_found_error(e: GLib.Error) -> bool:
    return e.matches(Gio.io_error_quark(), Gio.IOErrorEnum.NOT_FOUND)

def is_timeout_error(e: GLib.Error) -> bool:
    return (e.matches(Gio.DBusError.quark(), Gio.DBusError.TIMED_OUT) or
            e.matches(Gio.io_error_quark(), Gio.IOErrorEnum.TIMED_OUT))

i = 0
while i < 7:
    try:
        manager = Gio.DBusProxy.new_for_bus_sync(Gio.BusType.SYSTEM,
                                                 Gio.DBusProxyFlags.NONE, None,
                                                 FPRINT_NAMESPACE,
                                                 FPRINT_PATH + '/Manager',
                                                 FPRINT_NAMESPACE + '.Manager',
                                                 None)
        break
    except GLib.Error as e:
        if is_not_found_error(e):
            print('[INFO] Cannot connect to dbus interface. Skip updating.')
            exit()
        if not is_timeout_error(e):
            print('[INFO] Get an non timeout error.')
            raise e
        print('[INFO] Waiting for ControlVault3 Plus firmware update to finish.')
        i += 1
        if i == 7:
            print('[INFO] Firmware updating took more time than expected, stop waiting and it should be finished in background.')
            exit()
