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

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

int
helper_open_discovery_socket(uint16_t discovery_port)
{
    struct addrinfo hints, *res;
    int fd, status;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET; // use ipv4
    hints.ai_socktype = SOCK_DGRAM; //set socket flag
    hints.ai_flags = AI_PASSIVE; // get my IP

    char discovery_port_str[6];
    sprintf(discovery_port_str, "%u", discovery_port);

    //get connection info for our computer
    if ((status = getaddrinfo(NULL, discovery_port_str, &hints, &res)) != 0)
    {
        LOGGER_CRIT("getaddrinfo: %s\n", gai_strerror(status));
        freeaddrinfo(res);
        exit(EXIT_FAILURE);
    }

    //creating socket
    fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    int yes = 1;

    // lose the pesky "Address already in use" error message
    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
    {
        LOGGER_CRIT("setsockopt: %s\n", strerror(errno));
        freeaddrinfo(res);
        exit(EXIT_FAILURE);
    }

    if (bind(fd, res->ai_addr, res->ai_addrlen) == -1)
    {
        LOGGER_CRIT("bind: %s\n", strerror(errno));
        freeaddrinfo(res);
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(res);

    LOGGER_INFO("opened discovery socket on port %u\n", discovery_port);

    return fd;
}