#include <iostream>
#include <cerrno>
#include <cstdlib>
#include <signal.h>
#include "log.hpp"
#include "Server.hpp"

static void sigint_handler(int sig);
static int main_loop = true;

int
main(int argc, char **argv)
{
    if (argc != 3) {
        LOG << "usage: " << argv[0] << " <port> <password>" << std::endl;
        return 1;
    }

    char *pEnd;
    long port = std::strtol(argv[1], &pEnd, 10);
    if (errno == ERANGE || *pEnd || port < 0 || port > 0xffff) {
        LOG << "incorrect port" << std::endl;
        return 1;
    }

    Server serv(port, argv[2]);

    if (serv.init()) {
        LOG << "omegasadge :(" << std::endl;
        return 1;
    }

    signal(SIGINT, sigint_handler);
    while (main_loop && !serv.wait()) {}

    return 0;
}

static void
sigint_handler(int)
{
    main_loop = false;
}
