#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import dbus
import signal
import logging
import sys
import os

from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
from gi.repository import GLib

def overtime_handler():
    logging.debug("[kylin-upgrade-poweroff]: is over time.")
    GLib.MainLoop().quit()


SYSUPGRADE_DBUS_INTERFACE = "com.kylin.systemupgrade.interface"
SYSUPGRADE_DBUS_SERVICE = "com.kylin.systemupgrade"
SYSUPGRADE_DBUS_PATH = "/com/kylin/systemupgrade"

def signal_handler_term(signal, frame):
    logging.warning("[kylin-upgrade-poweroff]: signal %d received, will stop", signal)
    sys.exit(0)

if __name__ == "__main__":

    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    signal.signal(signal.SIGINT,signal_handler_term)
    os.unsetenv("DISPLAY")

    bus = dbus.SystemBus()
    proxy = bus.get_object(SYSUPGRADE_DBUS_SERVICE, SYSUPGRADE_DBUS_PATH)
    bus_interface = dbus.Interface(proxy, dbus_interface=SYSUPGRADE_DBUS_INTERFACE)
    
    GLib.timeout_add_seconds(3000,overtime_handler)

    func_next_install_on_shutdown = bus_interface.get_dbus_method("NextInstallOnShutdown")
    if func_next_install_on_shutdown != None:
        ret,info = func_next_install_on_shutdown()
        if ret != 0:
            logging.error("[kylin-upgrade-poweroff]: NextInstallOnShutdown err[%d][%s].",ret, info)
            GLib.MainLoop().quit()

        GLib.MainLoop().run()
    else:
        logging.error("[kylin-upgrade-poweroff]: method  not exits.")