#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>

#include <logger.h>
#include <helpers.h>

int
helper_bind_tcp_server(char* addr, uint16_t port, int max_client_backlog)
{
    char port_str[6];
    sprintf(port_str, "%d", port);

    struct addrinfo hints, *res;
    int fd;
    int status;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    if ((status = getaddrinfo(addr, port_str, &hints, &res)) != 0)
    {
        LOG_ERROR("getaddrinfo: %s\n", gai_strerror(status));
        return -1;
    }

    fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

    if ((status = bind(fd, res->ai_addr, res->ai_addrlen)) == -1)
    {
        LOG_ERROR("error binding socket: %s\n", strerror(errno));
        freeaddrinfo(res);
        return -1;
    }

    if ((status = listen(fd, max_client_backlog)) == -1)
    {
        LOG_ERROR("error setting up listener: %s\n", strerror(errno));
        freeaddrinfo(res);
        return -1;
    }

    freeaddrinfo(res);

    return fd;
}