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

int main(const int argc, const char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "usage: server <path> <mode>\n");
        return 1;
    }

    const char *path = argv[1];
    const char *mode = argv[2];

    int fd;
    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "unable to create socket: %s\n", strerror(errno));
        return 1;
    }

    struct sockaddr_un addr = {.sun_family = AF_UNIX};
    strcpy(addr.sun_path, path);
    if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) != 0) {
        fprintf(stderr, "unable to bind socket: %s\n", strerror(errno));
        close(fd);
        return 1;
    }

    if (listen(fd, 4) != 0) {
        fprintf(stderr, "unable to listen on socket: %s\n", strerror(errno));
        close(fd);
        return 1;
    }

    size_t len = 4096;
    char *line = malloc(len);
    while (1) {
        int client_fd;
        if ((client_fd = accept(fd, NULL, NULL)) == -1) {
            fprintf(stderr, "unable to accept connection: %s\n", strerror(errno));
            break;
        }

        FILE *client;
        if ((client = fdopen(client_fd, "w+")) == NULL) {
            fprintf(stderr, "unable open stream: %s\n", strerror(errno));
            close(client_fd);
            continue;
        }

        for (int n = 0; getline(&line, &len, client) > 0; n++) {
            if (n % 2 == 1) {
                fprintf(client, "%s\n", mode);
            }
        }

        fclose(client);
    }

    free(line);
    close(fd);
    unlink(path);
}
