#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

#define FIFO_CMD "/tmp/es2_cmd"
#define FIFO_OUT "/tmp/es2_out"

int main(void)
{
    char line[256];

    while (1) {
        printf("Comando (date/whoami/quit): ");
        fflush(stdout);

        if (!fgets(line, sizeof(line), stdin)) break;
        line[strcspn(line, "\n")] = '\0';

        if (strcmp(line, "quit") == 0) break;
        if (strcmp(line, "date") != 0 && strcmp(line, "whoami") != 0) {
            printf("Comandi validi: date, whoami\n");
            continue;
        }

        /*
         * Apertura non bloccante: ritorna -1 con ENXIO se nessun lettore
         * ha ancora aperto la FIFO (executor non pronto).
         */
        int fd_cmd;
        while (1) {
            fd_cmd = open(FIFO_CMD, O_WRONLY | O_NONBLOCK);
            if (fd_cmd != -1) break;
            if (errno == ENXIO || errno == ENOENT) {
                printf("[command] Executor non disponibile, attendo 5s…\n");
                sleep(5);
            } else {
                perror("open cmd"); exit(EXIT_FAILURE);
            }
        }

        write(fd_cmd, line, strlen(line));
        write(fd_cmd, "\n", 1);
        close(fd_cmd);

        /*
         * Apertura bloccante: si sincronizza con executor che apre FIFO_OUT
         * in scrittura una volta completato il comando.
         */
        int fd_out = open(FIFO_OUT, O_RDONLY);
        if (fd_out == -1) { perror("open out"); continue; }

        printf("[risposta] ");
        char buf[4096];
        ssize_t n;
        while ((n = read(fd_out, buf, sizeof(buf) - 1)) > 0) {
            buf[n] = '\0';
            printf("%s", buf);
        }
        printf("\n");
        close(fd_out);
    }

    return 0;
}
