#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>

#define MYPORT 5555    // the port users will be connecting to

#define BACKLOG 10     // how many pending connections queue will hold

#define BUF_LEN 200

int main(void)
{
        int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
        struct sockaddr_in my_addr;    // my address information
        struct sockaddr_in their_addr; // connector's address information
        int sin_size;
        int yes = 1;
        int retval;

        sockfd = socket(PF_INET, SOCK_STREAM, 0); // do some error checking!

        // tento radek zpusobi, ze pri opakovanem restartu serveru, bude volani
        // funkce bind() uspesne, kdo neveri, at ho zakomentuje :))
        if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1) {
            perror("setsockopt");
            exit(1);
        }
        
        my_addr.sin_family = AF_INET;         // host byte order
        my_addr.sin_port = htons(MYPORT);     // short, network byte order
        my_addr.sin_addr.s_addr = INADDR_ANY; // auto-fill with my IP
        memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct

        retval = bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr));
        if (retval != 0) {
                perror("bind");
                exit(1);
        }

        while (1) {
                char *msg = "Hello, this is server\n";
                size_t len;
                char buffer[BUF_LEN];

                retval = listen(sockfd, BACKLOG);
                if (retval != 0) {
                        perror("listen");
                        exit(1);
                }
                
                printf("Server is waiting for connection\n");

                sin_size = sizeof(struct sockaddr_in);
                new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);

                if (new_fd < 0) {
                        perror("accept");
                        exit(1);
                }


                printf("Client connected from %s:%d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port));
                send(new_fd, msg, strlen(msg), 0);
                
                while ((len = recv(new_fd, buffer, BUF_LEN-1, 0)) > 0) {
                        buffer[len] = '\0'; /* mark end of string */
                        printf("Message from client: %s\n", buffer);
                }
                printf("Client %s:%d closed connection\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port));
                close(new_fd);
        }
}