/*
 * @Author: yushuoqi yushuoqi@kylinos.cn
 * @Date: 2024-04-11 20:24:44
 * @LastEditors: yushuoqi yushuoqi@kylinos.cn
 * @LastEditTime: 2024-04-18 21:28:14
 * @FilePath: /kaiming/app/dbus/KMSystemServerAdaptor.cpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * 
 * Copyright (c) KylinSoft  Co., Ltd. 2024. All rights reserved.
 *
 * kaiming is licensed under the GPL v2.0+.
 * 
 * See the LICENSE file for more details.
 */
/**
 * @brief main.cpp
 */

#include "dbus/kmsysteminterface.h"

#include <gio/gio.h>
#include <stdlib.h>
#include <syslog.h>
#include <unistd.h>

#include <functional>
#include <iostream>
#include <list>
#include <memory>
#include <string>
#include <thread>

#include "app/info/KMInfoCommand.h"
#include "app/search/KMSearch.h"
#include "app/install/KMInstall.h"
#include "app/uninstall/KMUninstall.h"
#include "app/update/KMUpdate.h"
#include "common/KMLogger.h"
#include "common/KMError.h"
#include "common/KMPackageManager.h"
#include "common/KMFileUtils.h"
#include "common/KMFolder.h"

using namespace std;

#define KAIMING_DBUS_SERVICE "org.kylin.kaiming"
#define KAIMING_DBUS_PATH "/org/kylin/kaiming"
#define KAIMING_DBUS_INTERFACE "org.kylin.kaiming.interface"

static std::map<int, std::string> errorCodes = {
    { KM_ERROR_NO, "没有错误，操作成功" },
    { KM_ERROR_CHECK_ENV_FAILED, "检测系统环境失败" },
    { KM_ERROR_GET_SUMMARY_COMMIT_FAILED, "得到摘要commit失败" },
    { KM_ERROR_INVALID_ARGS, "非法传入参数" },
    { KM_ERROR_NEED_NEW_VERSION, "软件包或运行时需要更新的版本" },
    { KM_ERROR_ALREADY_INSTALLED, "系统已安装该软件包" },
    { KM_ERROR_NOT_INSTALLED, "系统未安装软件包" },
    { KM_ERROR_INSTALL_ONLY_PULLED, "软件包或运行时只拉取到本地仓库，但不安装" },
    { KM_ERROR_DIFFERENT_REMOTE, "软件包或运行时已安装，但是来自于不同的远程仓库源" },
    { KM_ERROR_INSTALL_SKIPPED, "软件包运行或软件或运行时因为更早的错误跳过安装" },
    { KM_ERROR_REMOTE_NOT_FOUND, "未找到具体的远程仓库源" },
    { KM_ERROR_RUNTIME_NOT_FOUND, "未找到运行时" },
    { KM_ERROR_REF_NOT_FOUND, "未找到完整的ref引用" },
    { KM_ERROR_REF_COMMIT_NOT_FOUND, "未找到ref对应的commit信息" },
    { KM_ERROR_DOWNGRADE, "拉取的commit是一个更新包，但更新包不被允许安装" },
    { KM_ERROR_INVALID_REF, "非法的ref引用" },
    { KM_ERROR_INVALID_DATA, "非法的数据" },
    { KM_ERROR_SETUP_FAILED, "沙箱建立失败" },
    { KM_ERROR_EXPORT_FAILED, "导出数据失败" },
    { KM_ERROR_REMOTE_USED, "远程仓库不允许卸载" },
    { KM_ERROR_RUNTIME_USED, "运行时不允许被卸载" },
    { KM_ERROR_INVALID_NAME, "非法的软件包、运行时或仓库源名称" },
    { KM_ERROR_OUT_OF_SPACE, "磁盘用尽，需要更多磁盘空间" },
    { KM_ERROR_WRONG_USER, "错误用户试图操作，比如非root用户试图执行root权限操作" },
    { KM_ERROR_NOT_CACHED, "得到摘要失败" },
    { KM_ERROR_PERMISSION_DENIED, "由于系统策略，该操作不被允许" },
    { KM_ERROR_DECOMPRESSION_FAILED, "文件解压失败" },
    { KM_ERROR_CURL_DOWNLOAD_FAILED, "curl下载文件失败" },
    { KM_ERROR_LOAD_FILE_FAILED, "加载文件失败" },
    { KM_ERROR_GET_SUBSUMMARY_GVARIANT_FAILED, "解析摘要信息失败" },
    { KM_ERROR_GET_REF_INFO_FAILED, "获取ref信息失败" },
    { KM_ERROR_NO_COLLECTIONID, "没有collection id" },
    { KM_ERROR_NOTHING_TO_DO, "无事可做" },
    { KM_ERROR_GET_COMMIT_DATA_FAILED, "获取commit数据失败" },
    { KM_ERROR_DEPLOY_DATA_FAILED, "部署数据到系统失败" },
    { KM_ERROR_FOUND_REMOTE_REF_FAILED, "未找到远程仓库对应的ref" },
    { KM_ERROR_DELETE_EXPORT_FILES_FAILED, "删除exports文件失败" },
    { KM_ERROR_DELETE_DIRECTORY_FAILED, "删除目录失败" },
    { KM_ERROR_DELETE_DEPLOY_TAG_FAILED, "删除deploy tag失败" },
    { KM_ERROR_DELETE_REF_TAG_FAILED, "删除ref tag失败" },
    { KM_ERROR_PRUNE_REPO_FAILED, "精简仓库失败" },
    { KM_ERROR_NOT_NEED_UPDATE, "不需要更新" },
    { KM_ERROR_LOAD_METADATA_FILE_FAILED, "加载 metadata 文件失败" },
    { KM_ERROR_UNINSTALL_FAILED, "卸载应用失败" },
    { KM_ERROR_DELETE_DIRECTORY_FAILED, "删除目录失败"},
    { KM_ERROR_NO_MD5_FILES, "签名文件不存在"},
    { KM_ERROR_SIGN_FAILED, "验签失败"},
};

static std::string getErrorMessage(int errorCode)
{
    if (errorCodes.find(errorCode) != errorCodes.end())
    {
        return errorCodes[errorCode];
    }
    else
    {
        return "未知错误";
    }
}

typedef struct _PackageInfo
{
    std::string name;
    std::string branch;
    std::string version;
    size_t packageSize;
} packageInfo;

typedef struct _AdaptorProgressStatus
{
    std::string refId;
    int progress;
    std::string speed;
    int timeout;
} AdaptorProgressStatus;

typedef enum
{
    KM_INSTALL_OPERATION = 0, // 安装操作
    KM_UPDATE_OPERATION,      // 升级操作
    KM_UNINSTALL_OPERATION,   // 卸载操作
} KMOperationType;

typedef std::function<void(AdaptorProgressStatus progressStatus)> progressCallBack;

class KMSystemServerAdaptor
{
public:
    KMSystemServerAdaptor()
    {
        m_install = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_installOfflinePackage = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_update = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_uninstall = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_isUpgradable = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_kmLocalInfo = shared_ptr<KMInfoCommand>(new KMInfoCommand());
        m_kmRemoteInfo = shared_ptr<KMSearch>(new KMSearch());
        m_isInstalled = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_getRemoteSummary = shared_ptr<KMPackageManager>(new KMPackageManager());
        m_folder = shared_ptr<KMFolder>(new KMFolder());
    }

    ~KMSystemServerAdaptor() { }

    gboolean install(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
    {
        kmlogger.info("begin call install api, m_installRunningFlag=%d", m_installRunningFlag);
        
        if (m_installRunningFlag)
        {
            return false;
        }

        m_installRunningFlag = true;

        // 创建回调函数，负责发送信号
        std::function<void(const std::string &)> callback = [this, object](const std::string &progressJson)
        {
            // 发送信号，这里使用模拟的数据
            AdaptorProgressStatus ps;

            kmlogger.info("receive jsonData: %s", progressJson.c_str());

            // 发送 progresschangesignal 信号
            g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
        };

        kmlogger.info("begin install");

        int installErrorNumber;

        std::cout << "Install thread!" << std::endl;
        // 调用真实安装函数，并传递回调函数,不阻塞主线程，在子线程中异步处理
        int ret = m_install->installSoftwareCenter(name, branch, installErrorNumber, callback);

        kmlogger.info("before emit install signal");

        // 发送 finishsignal 信号    g_signal_emit_by_name:通过名称触发一个信号
        g_signal_emit_by_name(object, "finishsignal", name, KM_INSTALL_OPERATION, ret, getErrorMessage(ret).c_str());

        this->m_installRunningFlag = false;
        kmlogger.info("end emit install signal, m_installRunningFlag = %d", this->m_installRunningFlag);

        bool sucess = false;
        if (ret == 0)
        {
            sucess = true;
        }

        // 返回布尔值表示成功或失败
        kaiming_interface_complete_install(object, invocation, sucess);

        return true;
    }

    gboolean installOfflinePackage(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
    {
        kmlogger.info("begin call install api, m_installRunningFlag=%d", m_installRunningFlag);
        if (m_installRunningFlag)
        {
            return false;
        }

        m_installRunningFlag = true;

        // 创建回调函数，负责发送信号
        std::function<void(const std::string &)> callback = [this, object](const std::string &progressJson)
        {
            // 发送信号，这里使用模拟的数据
            AdaptorProgressStatus ps;

            kmlogger.info("receive jsonData: %s", progressJson.c_str());

            // 发送 progresschangesignal 信号
            g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
        };

        kmlogger.info("begin install");

        int installErrorNumber;

        std::cout << "Install thread!" << std::endl;
        // 调用真实安装函数，并传递回调函数
        int ret = m_installOfflinePackage->installSoftwareCenter(name, branch, installErrorNumber, callback);
        kmlogger.info("before emit install signal");
        // 发送 finishsignal 信号    g_signal_emit_by_name:通过名称触发一个信号
        g_signal_emit_by_name(object, "finishsignal", name, KM_INSTALL_OPERATION, ret, getErrorMessage(ret).c_str());
        this->m_installRunningFlag = false;
        kmlogger.info("end emit install signal, m_installRunningFlag = %d", this->m_installRunningFlag);

        bool sucess = false;
        if (ret == 0)
        {
            sucess = true;
        }

        // 返回布尔值表示成功或失败  函数名称与xml自动生成的.c中的函数名称一致
        kaiming_interface_complete_install_offline_package(object, invocation, sucess);

        return true;
    }

    gboolean update(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
    {
        kmlogger.info("begin call update api, m_updateRunningFlag=%d", m_updateRunningFlag);

        if (m_updateRunningFlag)
        {
            return false;
        }

        m_updateRunningFlag = true;

        // 创建回调函数，负责发送信号
        std::function<void(const std::string &)> updatecallback = [this, object](const std::string &progressJson)
        {
            // 发送信号，这里使用模拟的数据
            AdaptorProgressStatus ps;

            kmlogger.info("receive jsonData: %s", progressJson.c_str());

            // 发送 progresschangesignal 信号
            g_signal_emit_by_name(object, "progresschangesignal", progressJson.c_str());
        };

        kmlogger.info("begin update");

        int updateErrorNumber;
       
        std::cout << "update thread!" << std::endl;
        // 调用真实安装函数，并传递回调函数,不阻塞主线程，在子线程中异步处理
        int ret = m_update->updateSoftwareCenter(name, branch, updateErrorNumber, updatecallback);
        kmlogger.info("before emit update signal");

        // 发送 finishsignal 信号    g_signal_emit_by_name:通过名称触发一个信号
        g_signal_emit_by_name(object, "finishsignal", name, KM_UPDATE_OPERATION, ret, getErrorMessage(ret).c_str());

        this->m_updateRunningFlag = false;
        kmlogger.info("end emit update signal, m_updateRunningFlag = %d", this->m_updateRunningFlag);

        bool sucess = false;
        if (ret == 0)
        {
            sucess = true;
        }

        // 返回布尔值表示成功或失败
        kaiming_interface_complete_update(object, invocation, sucess);

        return true;
    }

    gboolean uninstall(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name, const gchar *branch)
    {
        kmlogger.info("begin call uninstall api, m_installRunningFlag=%d", m_installRunningFlag);

        if (m_uninstallRunningFlag)
        {
            return false;
        }

        m_uninstallRunningFlag = true;

        int uninstallErrorNumber;
        kmlogger.info("uninstall thread!");

        // 调用真实卸载函数，并传递回调函数
        int ret = m_uninstall->uninstallSoftwareCenter(name, uninstallErrorNumber);
        kmlogger.info("before emit uninstall signal");

        // 发送 finishsignal 信号    g_signal_emit_by_name:通过名称触发一个信号
        g_signal_emit_by_name(object, "finishsignal", name, KM_UNINSTALL_OPERATION, ret, getErrorMessage(ret).c_str());
        kmlogger.info("end emit uninstall signal");

        this->m_uninstallRunningFlag = false;
        kmlogger.info("end emit uninstall signal, m_uninstallRunningFlag = %d", this->m_uninstallRunningFlag);

        bool sucess = false;
        if (ret == 0)
        {
            sucess = true;
        }

        // 返回布尔值表示成功或失败
        kaiming_interface_complete_uninstall(object, invocation, sucess);

        return true;
    }

    gboolean getLocalInfomation(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
    {
        kmlogger.info("begin call getLocalInfo api");

        int errorCode;
        string localInfoJson = m_kmLocalInfo->getLocalInfo(name, errorCode);

        kmlogger.info("before emit getLocalInfo signal");
        // 发送 getlocalinfosignal 信号
        g_signal_emit_by_name(object, "getlocalinfosignal", name, localInfoJson.c_str(), errorCode, getErrorMessage(errorCode).c_str());
        kmlogger.info("end emit getLocalInfo signal");

        // 创建一个 GVariant 来封装字符串
        GVariant* result = g_variant_new("(s)", localInfoJson.c_str());

        // 返回结果给调用方
        g_dbus_method_invocation_return_value(invocation, result);

        return TRUE;
    }

    /*
     * 软件商店通过直接返回字符串中branch是否为空判断查询结果是否正确，而不是通过发出的信号
     *
     * branch为空： 返回信息失败
     * branch不为空： 返回信息正确后，另外商店也能获取到发布平台发布的应用信息，商店就可以正确显示该应用
     */
    gboolean getRemoteInfomation(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
    {
        kmlogger.info("begin call getRemoteInfo api");

        int errorCode;

        string remoteInfoJson = m_kmRemoteInfo->getRemoteInfo(name, errorCode);

        kmlogger.info("before emit getRemoteInfo signal");
        // 发送 getremoteinfosignal 信号
        g_signal_emit_by_name(object, "getremoteinfosignal", name, remoteInfoJson.c_str(), errorCode, getErrorMessage(errorCode).c_str());
        kmlogger.info("end emit getRemoteInfo signal");

        // 创建一个 GVariant 来封装字符串
        GVariant* result = g_variant_new("(s)", remoteInfoJson.c_str());

        // 返回结果给调用方
        g_dbus_method_invocation_return_value(invocation, result);

        return TRUE;
    }

    gboolean isInstalled(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
    {
        kmlogger.info("begin call isInstalled api");

        if (*name == '\0')
        {
            // 返回布尔值表示成功或失败
            kaiming_interface_complete_is_installed(object, invocation, false);
            return false;
        }

        int errorCode;
        bool isInstall = false;

        errorCode = m_isInstalled->isInstalled(name);
        if (errorCode == KM_ERROR_NO)
        {
            isInstall = true;
        }

        kmlogger.info("before emit isInstalled signal");
        // 发送 isinstalledsignal 信号
        g_signal_emit_by_name(object, "isinstalledsignal", name, errorCode, 0, getErrorMessage(errorCode).c_str());
        kmlogger.info("end emit isInstalled signal");

        bool sucess = false;
        if (isInstall == true)
        {
            sucess = true;
        }

        // 返回生成的信息字符串
        kaiming_interface_complete_is_installed(object, invocation, sucess);

        return true;
    }

    gboolean isUpgradable(KaimingInterface *object, GDBusMethodInvocation *invocation, const gchar *name)
    {
        kmlogger.info("begin call isUpgradable api");

        if (*name == '\0')
        {
            // 返回布尔值表示成功或失败
            kaiming_interface_complete_is_upgradable(object, invocation, false);
            return false;
        }

        int errorCode;
        bool isUpgradabled = false;

        errorCode = m_isUpgradable->isUpgradabled(name);
        if (errorCode == KM_ERROR_NO)
        {
            isUpgradabled = true;
        }

        kmlogger.info("before emit isUpgradable signal");
        // 发送 isupgradablesignal 信号
        g_signal_emit_by_name(object, "isupgradablesignal", name, errorCode, 0, getErrorMessage(errorCode).c_str());
        kmlogger.info("end emit isUpgradable signal");


        bool sucess = false;
        if (isUpgradabled == true)
        {
            sucess = true;
        }

        // 返回生成的信息字符串
        kaiming_interface_complete_is_upgradable(object, invocation, sucess);

        return true;
    }

    gboolean getRemoteSummary(KaimingInterface *object, GDBusMethodInvocation *invocation)
    {
        KMFolder folder;
        folder.ensureRepoForSudo(false);

        kmlogger.info("begin call getRemoteSummary api");

        int errorCode;

        // 下载和解析清单依赖文件 summary.json
        fs::path repoPath = folder.getRepoPath(); // /opt/kaiming/repo

        KMOSTreeHandler ostreeManager(repoPath.string());

        string ostreeRepoUrl = ostreeManager.getRemoteUrl(REPO_NAME);
        std::string summaryUrl = ostreeRepoUrl.append("/").append("summary.json");

        fs::path basePath = folder.getPath();
        fs::path summaryJsonPath = basePath / "summary.json";
        bool isSummaryJsonExpired = KMFileUtils::isFileExpired(summaryJsonPath, 3600);
        errorCode = m_getRemoteSummary->getRemoteSummary(summaryUrl, isSummaryJsonExpired);

        kmlogger.info("before emit getRemoteSummary signal");
        // 发送 getremotesummarysignal 信号
        g_signal_emit_by_name(object, "getremotesummarysignal", summaryUrl, errorCode, getErrorMessage(errorCode).c_str());
        kmlogger.info("end emit getRemoteSummary signal");

        bool sucess = false;
        if (errorCode == KM_ERROR_NO)
        {
            sucess = true;
        }

        // 返回生成的信息字符串
        kaiming_interface_complete_is_upgradable(object, invocation, sucess);

        return TRUE;
    }

    // 静态适配器方法，用于连接 GDBus 信号   KaimingInterface需与xml自动生成的.c中的一致
    static gboolean handleInstall(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                            const gchar *name, const gchar *branch, gpointer user_data)
    {
        // 将 user_data 转换为 KMSystemServerAdaptor 实例
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->install(object, invocation, name, branch);
    }

    static gboolean handleInstallOfflinePackage(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                            const gchar *name, const gchar *branch, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->installOfflinePackage(object, invocation, name, branch);
    }

    static gboolean handleUpdate(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                         const gchar *name, const gchar *branch, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->update(object, invocation, name, branch);
    }

    static gboolean handleUninstall(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                                 const gchar *name, const gchar *branch, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->uninstall(object, invocation, name, branch);
    }

    static gboolean handleGetLocalInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                          const gchar *name, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->getLocalInfomation(object, invocation, name);
    }
    
    static gboolean handleGetRemoteInfo(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                         const gchar *name, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->getRemoteInfomation(object, invocation, name);
    }

    static gboolean handleIsInstalled(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                         const gchar *name, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->isInstalled(object, invocation, name);
    }

    static gboolean handleIsUpgradable(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                         const gchar *name, gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->isUpgradable(object, invocation, name);
    }

    static gboolean handleGetRemoteSummary(KaimingInterface *object, GDBusMethodInvocation *invocation,
                                          gpointer user_data)
    {
        KMSystemServerAdaptor *instance = static_cast<KMSystemServerAdaptor *>(user_data);
        return instance->getRemoteSummary(object, invocation);
    }

private:
    shared_ptr<KMPackageManager> m_install;     // 安装
    shared_ptr<KMPackageManager> m_installOfflinePackage;     // 离线安装
    shared_ptr<KMPackageManager> m_uninstall;      // 卸载
    shared_ptr<KMPackageManager> m_update;            // 更新
    shared_ptr<KMInfoCommand> m_kmLocalInfo;  // 获取本地信息
    shared_ptr<KMSearch> m_kmRemoteInfo; // 获取远程信息
    shared_ptr<KMPackageManager> m_isInstalled; // 开明包管理
    shared_ptr<KMPackageManager> m_isUpgradable; // 开明包是否可更新
    shared_ptr<KMPackageManager> m_getRemoteSummary; // 是否更新summary.json
    shared_ptr<KMFolder> m_folder;

    std::thread m_installThread;
    bool m_installRunningFlag = false;

    std::thread m_updateThread;
    bool m_updateRunningFlag = false;

    std::thread m_uninstallThread;
    bool m_uninstallRunningFlag = false;

    std::thread m_localInfoThread;
    std::thread m_remoteInfoThread;
    std::thread m_isInstalledThread;
    std::thread m_isUpgradableThread;
};

// 当总线获取成功时的回调
static void on_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data)
{
    GError *error = NULL;
    // 获取 KMSystemServerAdaptor 实例
    KMSystemServerAdaptor *handler = static_cast<KMSystemServerAdaptor *>(user_data); 
    // 创建一个新的 Service 对象  需与xml自动生成的.c中的一致
    KaimingInterface *service = kaiming_interface_skeleton_new();           
    // 将 Service 对象的方法调用与 KMSystemServerAdaptor 的方法连接起来   "handle-install-offline-package"需与xml自动生成的.c中的一致
    g_signal_connect(service, "handle-install", G_CALLBACK(KMSystemServerAdaptor::handleInstall), handler);
    g_signal_connect(service, "handle-install-offline-package", G_CALLBACK(KMSystemServerAdaptor::handleInstallOfflinePackage), handler);
    g_signal_connect(service, "handle-update", G_CALLBACK(KMSystemServerAdaptor::handleUpdate), handler);
    g_signal_connect(service, "handle-uninstall", G_CALLBACK(KMSystemServerAdaptor::handleUninstall), handler);
    g_signal_connect(service, "handle-get-local-info", G_CALLBACK(KMSystemServerAdaptor::handleGetLocalInfo), handler);
    g_signal_connect(service, "handle-get-remote-info", G_CALLBACK(KMSystemServerAdaptor::handleGetRemoteInfo), handler);
    g_signal_connect(service, "handle-is-installed", G_CALLBACK(KMSystemServerAdaptor::handleIsInstalled), handler);
    g_signal_connect(service, "handle-is-upgradable", G_CALLBACK(KMSystemServerAdaptor::handleIsUpgradable), handler);
    g_signal_connect(service, "handle-get-remote-summary", G_CALLBACK(KMSystemServerAdaptor::handleGetRemoteSummary), handler);

    // 将 Service 对象导出到 D-Bus 连接上
    g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(service), connection, KAIMING_DBUS_PATH, &error);
    if (error)
    {
        std::cerr << "Failed to export interface: " << error->message << std::endl;
        g_clear_error(&error);
    }
}

int main(int argc, char *argv[])
{
    // 创建主循环对象
    GMainLoop *loop; 
    guint owner_id;

    // 创建 KMSystemServerAdaptor 实例
    KMSystemServerAdaptor handler;

    // 将 handler 作为 user_data 传递
    owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, KAIMING_DBUS_SERVICE, G_BUS_NAME_OWNER_FLAGS_NONE,
                              on_bus_acquired, NULL, NULL, &handler, NULL);

    // 创建主循环
    loop = g_main_loop_new(NULL, FALSE); 
    // 进入循环
    g_main_loop_run(loop);               

    // 取消 D-Bus 名称的所有权 释放资源
    g_bus_unown_name(owner_id); 
    // 释放 GMainLoop 对象
    g_main_loop_unref(loop);

    return 0;
}
