#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/wait.h>

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

int main(void)
{
    /* Crea le FIFO (ignora EEXIST) */
    if (mkfifo(FIFO_CMD, 0660) == -1 && errno != EEXIST) {
        perror("mkfifo cmd"); exit(EXIT_FAILURE);
    }
    if (mkfifo(FIFO_OUT, 0660) == -1 && errno != EEXIST) {
        perror("mkfifo out"); exit(EXIT_FAILURE);
    }

    printf("[executor] In ascolto su %s …\n", FIFO_CMD);

    for (;;) {
        
        int fd_in = open(FIFO_CMD, O_RDONLY);
        if (fd_in == -1) { perror("open cmd"); break; }

        int fd_out = open(FIFO_OUT, O_WRONLY);
        if (fd_out == -1) { perror("open out"); close(fd_in); break; }

        /* Leggi il comando (stringa breve, EOF alla chiusura lato command) */
        char cmd[256] = {0};
        ssize_t n = read(fd_in, cmd, sizeof(cmd) - 1);
        close(fd_in);
        if (n <= 0) { close(fd_out); continue; }
        cmd[strcspn(cmd, "\n")] = '\0';

        printf("[executor] Ricevuto: '%s'\n", cmd);

        /* Mappa comando → eseguibile */
        char *exe = NULL;
        if      (strcmp(cmd, "date")   == 0) exe = "date";
        else if (strcmp(cmd, "whoami") == 0) exe = "whoami";

        if (!exe) {
            const char *err = "ERRORE: comando non riconosciuto\n";
            write(fd_out, err, strlen(err));
            close(fd_out);
            continue;
        }

        /* Fork + exec con stdout rediretto su FIFO_OUT */
        pid_t pid = fork();
        if (pid == -1) { perror("fork"); close(fd_out); continue; }

        if (pid == 0) {
            dup2(fd_out, STDOUT_FILENO);
            close(fd_out);
            execlp(exe, exe, NULL);
            perror("exec"); exit(EXIT_FAILURE);
        }

        waitpid(pid, NULL, 0);
        close(fd_out);   /* EOF per il command */
    }

    unlink(FIFO_CMD);
    unlink(FIFO_OUT);
    return 0;
}
