#include <csignal>
#include <iostream>

#include "server.h"
#include "version.h"
#include <of_path.h>

#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#include <windows.h>
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
#endif

#if defined(GRAB_CRASH)
#include <crashelper.h>
#endif

#ifdef USE_BOOST
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <filesystem>
namespace fs = std::filesystem;
#endif

void msignal_handler(int signal)
{
    fc_recovery_color();
    exit(signal);
}

int main(int argc, char* argv[])
{
#if defined(GRAB_CRASH)
    auto config_dir = COfPath::get_config_dir("transm", true);
    auto err = fs::path(config_dir).append("errs").string();
    backward::SetDumpFileSavePath(err);
    backward::SetDumpLogSavePath(err);
    CRASHELPER_MARK_ENTRY();
    sh.register_user_sig_handler([](int sig) { msignal_handler(sig); });
#endif

#ifdef _WIN32
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    DWORD mode;
    GetConsoleMode(hConsole, &mode);
    mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
    SetConsoleMode(hConsole, mode);
#endif

    std::shared_ptr<int> deleter(new int(), [](int* p) {
        fc_recovery_color();
        delete p;
    });

    TLOGI("Build At {} {} under {} on {}", __DATE__, __TIME__, VERSION_GIT_COMMIT, VERSION_GIT_BRANCH);
    int port = 9898;
    if (argc < 2) {
        TLOGI("Use Default Port:{}", port);
    } else {
        std::string str_port(argv[1]);
        port = std::stoi(str_port);
        TLOGI("Use Port:{}", port);
    }
    asio::io_context io_context;
    TransmServer server(io_context);
    if (!server.start(port)) {
        return -1;
    }
    io_context.run();
    return 0;
}
