#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/timerfd.h>
#include <sys/types.h>
#include <syslog.h>

#include "cJSON.h"
#include "dy_common.h"
#include "mqtt_session.h"

int load_server_config(mqtt_session_t *session, char *cfg_file)
{
    char *data = NULL;
    cJSON *root = NULL;
    int ret = -1;
    char addr[MAX_HOST_LEN]; ///<MQTT地址
    unsigned short port = 0;     ///<MQTT端口
    char user[MAX_USER_LEN]; ///<MQTT
    char pass[MAX_PASS_LEN]; ///<MQTT地址
    int lens = 0;

    if (cfg_file == NULL)
    {
        dy_syslog(LOG_ERR, "cfg_file not exist, use defaut MQTT server");
        goto out;
    }

    data = read_file_data_and_lens(cfg_file, &lens);
    if (data == NULL)
    {
        dy_syslog(LOG_ERR, "read cfg file %s error, load default", cfg_file);
        goto out;
    }

    root = cJSON_Parse(data);
    if (!root)
    {
        char *new = malloc(lens);
        if (new != NULL)
        {
            lnxall_decrypt_string((unsigned char *) data, lens, (unsigned char *) new);
            free(data);
            data = new;
            root = cJSON_Parse(data);
        }

        if (!root)
        {
            dy_syslog(LOG_ERR, "parse cfg file %s error, load default", cfg_file);
            goto out;
        }
    }

    GET_JSON_VALUE_STRING(root, "host", addr);
    GET_JSON_VALUE_INT(root, "port", port);
    GET_JSON_VALUE_STRING(root, "user", user);
    GET_JSON_VALUE_STRING(root, "pass", pass);
    char cafile_url[128] = {0}, certfile_url[128] = {0}, keyfile_url[128] = {0};
    GET_JSON_VALUE_STRING(root, "cafile", cafile_url);
    GET_JSON_VALUE_STRING(root, "certfile", certfile_url);
    GET_JSON_VALUE_STRING(root, "keyfile", keyfile_url);
    if (strlen(cafile_url))
    {
        char cafile[128] = {0};
        char certfile[128] = {0};
        char keyfile[128] = {0};
        char path[128] = {0};
        sprintf(path, "%s", CONFIG_MQTT_TLS_FILE_PATH);
        if (strlen(cafile_url))
        {
            mqtt_tls_file_overlow(cafile_url, path, cafile, 128);
        }
        if (strlen(certfile_url))
        {
            mqtt_tls_file_overlow(certfile_url, path, certfile, 128);
        }
        if (strlen(keyfile_url))
        {
            mqtt_tls_file_overlow(keyfile_url, path, keyfile, 128);
        }
        dy_syslog(LOG_DEBUG, "cafile:%s,certfile:%s,keyfile:%s", cafile, certfile, keyfile);
        mqtt_session_set_tls(session, cafile, certfile, keyfile);
    }
    mqtt_session_set_address(session, addr, port, user, pass);

    cJSON_Delete(root);
    ret = 0;

out:
    if (data)
    {
        free(data);
    }
    return ret;
}
