#include <fstream>

#include <util/folder/dirut.h>
#include <wmconsole/version3/wmcutil/args.h>
#include <wmconsole/version3/wmcutil/log.h>
#include "wmconsole/version3/wmcutil/http_server.h"

#include "config.h"
#include "monitor.h"
#include "service.h"

namespace NWebmaster {

static volatile bool gRunning = true;

static void OnTerminate(int = 0) {
    gRunning = false;
}

int Main(const TConfig &config) {
    InitNetworkSubSystem();

    // Manage signals
    signal(SIGPIPE, SIG_IGN);
    signal(SIGINT, OnTerminate);
    signal(SIGTERM, OnTerminate);

    TMonitor::Instance();

    TValidatorService validatorService(config);

    THttpServer httpServer(THttpServerOptions(config.HTTP_SERVER_PORT), &validatorService);

    // Wait for signals
    do {
        sleep(1);
    } while (gRunning);

    TMonitor::Instance().Shutdown();

    LOG_INFO("Exiting");

    return 0;
}

} //namespace NWebmaster

int main(int argc, const char** argv) {
    using namespace NWebmaster;

    int res = 1;

    TArgs::Init(argc, argv);
    TConfig config(TArgs::Opts());
    TArgs::ParseOpts();

    LOG_INFO("Started");
    try {
        config.Load();
        return NWebmaster::Main(config);
    } catch (std::exception& e) {
        LOG_CRIT("%s", e.what());
    }

    LOG_INFO("Finished");

    return res;
}
