/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "abstractserver.h"

#include <sys/stat.h>
#include <sys/types.h>

#include "utils/logger.h"

#define UNIX_PATH_MODE 0777

const std::string AbstractServer::socketFilePath_ = "/tmp/.kylin-ai-runtime-unix/" + std::to_string(getuid()) + "/";

AbstractServer::AbstractServer(const std::string &filePath) : filePath_(filePath) { checkSocketFilePath(); }

AbstractServer::~AbstractServer() { stopServer(); }
void AbstractServer::startServer() {
    GMainContext *context = g_main_context_new();
    g_main_context_push_thread_default(context);

    auto *guid = g_dbus_generate_guid();
    GError *error = nullptr;

    std::string unixPath = "unix:path=" + filePath_;
    server_ = g_dbus_server_new_sync(unixPath.c_str(),         /* address */
                                     G_DBUS_SERVER_FLAGS_NONE, /* flags */
                                     guid,                     /* guid */
                                     nullptr,                  /* GDBusAuthObserver */
                                     nullptr,                  /* GCancellable */
                                     &error);
    chmod(socketFilePath_.c_str(), UNIX_PATH_MODE);

    if (error) {
        g_printerr("Error creating server at address %s: %s\n", unixPath.c_str(), error->message);
        g_error_free(error);
        g_main_context_pop_thread_default(context);
        g_main_context_unref(context);
        return;
    }

    g_signal_connect(server_, "new-connection", G_CALLBACK(onNewConnection), this);

    g_dbus_server_start(server_);

    GMainLoop *loop = g_main_loop_new(context, FALSE);
    g_main_loop_run(loop);

    g_main_loop_unref(loop);
    g_object_unref(server_);
    g_free(guid);
    g_main_context_pop_thread_default(context);
    g_main_context_unref(context);
}

void AbstractServer::stopServer() {
    if (server_ == nullptr) {
        return;
    }

    g_dbus_server_stop(server_);
}

void AbstractServer::checkSocketFilePath() {
    if (pathExist(socketFilePath_)) {
        unlink(filePath_.c_str());
        return;
    }

    const char *socketPath = socketFilePath_.c_str();
    int len = strlen(socketPath);

    for (int i = 0; i < len; ++i) {
        if (socketPath[i] != '/') {
            continue;
        }

        char subdir[i + 1];
        strncpy(subdir, socketPath, i + 1);
        subdir[i + 1] = '\0';
        if (pathExist(subdir)) {
            continue;
        }

        if (errno = 0; int errorCode = mkdir(subdir, UNIX_PATH_MODE) != 0) {
            LOGE("Failed to create config server directory: {} {} {} {}.", errorCode, std::string(subdir), errno,
                 strerror(errno));
            return;
        }

        if (int errorCode = chmod(subdir, UNIX_PATH_MODE) != 0) {
            LOGE("Failed to chmod config server directory: {} {}.", errorCode, std::string(subdir));
        }
    }
}

bool AbstractServer::pathExist(const std::string &path) {
    struct stat st;
    if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) {
        return true;
    }
    return false;
}

gboolean AbstractServer::onNewConnection(GDBusServer * /* server */, GDBusConnection *connection, gpointer userData) {
    auto *server = static_cast<AbstractServer *>(userData);

    server->handleNewConnection(connection);
    server->closedHandlerId_ = g_signal_connect(connection, "closed", G_CALLBACK(server->onConnectionClosed), server);
    return true;
}

void AbstractServer::onConnectionClosed(GDBusConnection *connection, gboolean /* remotePeerVanished */,
                                        GError * /* error */, gpointer userData) {
    LOGI("Connection closed.");
    auto *server = static_cast<AbstractServer *>(userData);

    if (server->closedHandlerId_ > 0) {
        g_signal_handler_disconnect(connection, server->closedHandlerId_);
        server->closedHandlerId_ = 0;
    }
    server->handleDisconnection(connection);
    g_object_unref(connection);
}
