#include <syslog.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <systemd/sd-bus.h>
#include <unistd.h>
#include <fcntl.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <dbus/dbus.h>
#include <dbus/dbus-glib-lowlevel.h> /* for glib main loop */
int dbus_monitor1(void)
{
   
    DBusConnection *connection;
    DBusError error;
    dbus_error_init(&error);
    syslog(LOG_ERR,"WD--file=[%s]--fun=[%s]--line=[%d]-Connection Error:[%s]",__FILE__,__FUNCTION__,__LINE__,error.message);
    // Connect to session bus
    connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error);
    if (dbus_error_is_set(&error))
    {
        fprintf(stderr, "Connection Error (%s)\n", error.message);
        syslog(LOG_ERR,"WD--file=[%s]--fun=[%s]--line=[%d]-Connection Error:[%s]",__FILE__,__FUNCTION__,__LINE__,error.message);
        dbus_error_free(&error);
        return 1;
    }

    // Add a rule for incoming signals
    dbus_bus_add_match(connection, "type='signal',interface='org.freedesktop.login1.Manager'", &error);
    dbus_connection_flush(connection);

    if (dbus_error_is_set(&error))
    {
        fprintf(stderr, "Error adding D-Bus match rule (%s)\n", error.message);
        syslog(LOG_ERR,"WD--file=[%s]--fun=[%s]--line=[%d]-Connection Error:[%s]",__FILE__,__FUNCTION__,__LINE__,error.message);
        dbus_error_free(&error);
        return 1;
    }

    // Main event loop
    while (1)
    {
        DBusMessage *message;
        DBusMessageIter args;
        guint16 sigvalue;
        DBusDispatchStatus status = dbus_connection_read_write(connection, 1000); // 设置阻塞时间
        // Blocking call to receive a message
        message = dbus_connection_pop_message(connection);

        if (message != NULL)
        {
            if (dbus_message_is_signal(message, "com.kylin.MaintainMode", "BootModeChanged"))
            {
                // 读取参数
                if (!dbus_message_iter_init(message, &args))
                    fprintf(stderr, "消息没有参数！\n");
                else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args))
                    fprintf(stderr, "参数格式错误！\n");
                else
                {
                    dbus_message_iter_get_basic(&args, &sigvalue);
                    printf("获取信号的值： %d\n", sigvalue);
                    syslog(LOG_ERR, "WD--file=[%s]--fun=[%s]--line=[%d]-获取信号的值:[%d]", __FILE__, __FUNCTION__, __LINE__, sigvalue);
                     char command[255] = {};
                    if (sigvalue == 1) // 是进入运维模式
                    {
                        ////函数处理
                        ////获取到信号，do what you do.....
                        syslog(LOG_INFO, "------进入运维模式-----");
                        snprintf(command, sizeof(command), "%s %s", "/usr/ost-ex.d/boot_handle.sh","in");
                        if (system(command) == 0)
                        {
                            syslog(LOG_INFO, "copy success");
                        }
                        syslog(LOG_INFO, "------进入运维模式boot备份end-----");
                    }else if(sigvalue == 3){
                        syslog(LOG_INFO, "------进入运维模式-----");
                        snprintf(command, sizeof(command), "%s %s", "/usr/ost-ex.d/boot_handle.sh","out");
                        if (system(command) == 0)
                        {
                            syslog(LOG_INFO, "copy success");
                        }
                        syslog(LOG_INFO, "------进入运维模式boot备份end-----");
                    }
                }
            }
            // Free the received message
            dbus_message_unref(message);
        }
    }
    // Close the connection
    dbus_connection_unref(connection);
    return 0;
}
void copy(char *path, char *type)
{
    char command[255] = {};
    snprintf(command, sizeof(command), "%s %s %s", "/usr/ost-ex.d/copy.sh", type, path);
    if (system(command) == 0)
    {
        syslog(LOG_INFO, "copy success");
    }
}
void print_path_elements(xmlNode *node, char *type) {
    xmlNode *cur_node = NULL;
    for (cur_node = node; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE && strcmp((const char *)cur_node->name, "path") == 0) {
            printf("Path: %s\n", xmlNodeGetContent(cur_node));
            copy(xmlNodeGetContent(cur_node), type);
        }
        print_path_elements(cur_node->children, type);
    }
}
pthread_t boot_tid;
int main(int argc, char **argv) {
    xmlDoc *doc = NULL;
    xmlNode *root_element = NULL;
    xmlNode *restore_install_etc = NULL;
    xmlNode *restore_install_var=NULL;

    LIBXML_TEST_VERSION

    doc = xmlReadFile("/etc/restore.xml", NULL, 0);

    if (doc == NULL) {
        printf("Error: could not parse file %s", argv[1]);
        return 1;
    }
    if (!pthread_create(&boot_tid, NULL, dbus_monitor1, NULL))
    {
        syslog(LOG_INFO, "CALL");
    }
    root_element = xmlDocGetRootElement(doc);
    restore_install_etc = root_element->children;
    restore_install_var = restore_install_etc->next;

    while (restore_install_etc != NULL)
    {
        if (strcmp((const char *)restore_install_etc->name, "restore_install_etc") == 0)
        {
            print_path_elements(restore_install_etc->children,"etc");
            break;
        }
        restore_install_etc = restore_install_etc->next;
    }

    while (restore_install_var != NULL)
    {
        if (strcmp((const char *)restore_install_var->name, "restore_install_var") == 0)
        {
            print_path_elements(restore_install_var->children,"var");
            break;
        }
        restore_install_var = restore_install_var->next;
    }

    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}