#include "daemon.h"
#include "saas_push.h"

#include <library/cpp/sighandler/async_signals_handler.h>

int DaemonMain(int argc, const char** argv) {
    TString configPath;
    ui16 basePort = 0;
    ui16 controllerPort = 0;

    NLastGetopt::TOpts opts;
    opts.AddHelpOption('h');

    opts.AddLongOption('c', "config", "path to config")
        .Required()
        .RequiredArgument("<path>")
        .StoreResult(&configPath);

    opts.AddLongOption('p', "port", "base port")
        .StoreResult(&basePort);

    opts.AddLongOption('P', "controller-port", "controller port")
        .StoreResult(&controllerPort);

    opts.SetFreeArgsMax(0);
    NLastGetopt::TOptsParseResult parseResults(&opts, argc, argv);

    auto config = NSaasPush::ReadConfig(configPath, basePort, controllerPort);

    NSaasPush::TDaemon daemon(config);
    if (!daemon.Start()) {
        ythrow yexception() << "Can not start HTTP server";
    }

    SetAsyncSignalFunction(SIGHUP, [](int) { SendGlobalMessage<TMessageReopenLogs>(); });

    daemon.WaitStopped();
    return 0;
}
