#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <unistd.h>

int main()
{
    setgid(1000);
    setuid(1000);

    remove("/tmp/local.sock");

    int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("socket");
        return 0;
    }

    struct sockaddr_un un;
    un.sun_family = AF_UNIX;
    strncpy(un.sun_path, "/tmp/local.sock", sizeof(un.sun_path));

    if (bind(sockfd, (struct sockaddr*)&un, sizeof(un)) < 0)
    {
        perror("bind");
        return 1;
    }

    if (listen(sockfd, 10) < 0)
    {
        perror("listen");
        return 1;
    }

    while (1)
    {
        int fd = accept(sockfd, NULL, NULL);
        if (fd < 0)
        {
            perror("accept");
            return 1;
        }

        puts("New connection from client, sending hello");

        const char* message = "Hello, client!";
        write(fd, message, strlen(message));

        puts("Now waiting for client to message back");

        char buf[4096];
        ssize_t nread = read(fd, buf, sizeof(buf) - 1);
        if (nread >= 0)
        {
            buf[nread] = 0;
            printf("Message from client: %s\n", buf);
            if (!strcasecmp(buf, "exit"))
            {
                close(fd);
                close(sockfd);
                remove("/tmp/local.sock");
                return 0;
            }
        }
        else { printf("Error reading from client: %s\n", strerror(errno)); }

        puts("Transmission ended, closing connection");

        close(fd);
    }
}