#!/usr/bin/python3


import os
import subprocess
import dbus

class KareHook:

    def __init__(self):
        self.contrainer_conf = "/etc/kare-container"
        self.contrainer_name = self._get_container_name()
        self.dpkg_log = "/var/log/dpkg.log"
        self.package_info = subprocess.getoutput("cat {} | grep upgrade | grep {}".format(self.dpkg_log, self.contrainer_name))
        if self.package_info:
            self.upgrade()
            exit()
        self.package_info = subprocess.getoutput("cat {} | grep purge | grep {}".format(self.dpkg_log, self.contrainer_name))
        if self.package_info:
            self.purge()
            exit()
        self.package_info = subprocess.getoutput("cat {} | grep remove | grep {}".format(self.dpkg_log, self.contrainer_name))
        if self.package_info:
            self.purge()

    def _get_container_name(self):
        if os.path.exists(self.contrainer_conf) is False:
            exit()
        contrainer_name = subprocess.getoutput("cat {}".format(self.contrainer_conf))
        return contrainer_name
    
    def upgrade(self):
        version, upgrade_version = self.package_info.split()[-2:]
        if version == upgrade_version:
            exit()
        bus = dbus.SystemBus()
        proxy = bus.get_object(
            "com.kylin.kareAgent",
            "/com/kylin/kareAgent"
        )
        interface = dbus.Interface(
            proxy,
            dbus_interface="com.kylin.kareAgent"
        )
        interface.packager_version_replace(self.contrainer_name, upgrade_version)

    def purge(self):
        bus = dbus.SystemBus()
        proxy = bus.get_object(
            "org.kylin.kare",
            "/org/kylin/kare"
        )
        interface = dbus.Interface(
            proxy,
            dbus_interface="org.kylin.kare"
        )
        interface.remove(self.contrainer_name)


if __name__ == "__main__":
    kare_hook = KareHook()