#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 <dbus/dbus.h>
// #include <dbus/dbus-glib-lowlevel.h> /* for glib main loop */
#include <libxml/parser.h>
#include <libxml/tree.h>

void restore(char *path, char *type)
{
    char command[255] = {};
    snprintf(command, sizeof(command), "%s %s %s", "/usr/ost-ex.d/restore.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));
            restore(xmlNodeGetContent(cur_node), type);
        }
        print_path_elements(cur_node->children, type);
    }
}

int main(int argc, char **argv) {
    xmlDoc *doc = NULL;
    xmlNode *root_element = NULL;
    xmlNode *restore_sys_etc = NULL;
    xmlNode *restore_install_etc = NULL;
    xmlNode *restore_sys_var =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;
    }

    root_element = xmlDocGetRootElement(doc);
    restore_sys_etc = root_element->children;
    restore_install_etc = restore_sys_etc->next;
    restore_sys_var=restore_install_etc->next;
    restore_install_var=restore_sys_var->next;

    while (restore_sys_etc != NULL)
    {
        if (strcmp((const char *)restore_sys_etc->name, "restore_sys_etc") == 0)
        {
            print_path_elements(restore_sys_etc->children,"etc");
            break;
        }
        restore_sys_etc = restore_sys_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_sys_var != NULL)
    {
        if (strcmp((const char *)restore_sys_var->name, "restore_sys_var") == 0)
        {
            print_path_elements(restore_sys_var->children,"var");
            break;
        }
        restore_sys_var = restore_sys_var->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;
}