#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <err.h>
#include <errno.h>
#include "../lpi.h"     // for toInt()
                        // implemented in ../lpi.c

void handler(int sig, siginfo_t *siginfo, void *ucontext);

int
main(int argc, char *argv[])
{
    struct sigaction sa;
    char buf[BUFSIZ];
    int n, secs;

    if (argc != 2) {
        fprintf(stderr, "usage: %s seconds\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    if ((errno = toInt(argv[1], &secs)) != 0)
        err(EXIT_FAILURE, "toInt(%s)", argv[1]);

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_sigaction = handler;

    if (sigaction(SIGALRM, &sa, NULL) == -1)
        err(EXIT_FAILURE, "sigaction");

    printf("You have %d seconds to enter a line:\n", secs);
    alarm(secs);
    if ((n = read(STDIN_FILENO, buf, BUFSIZ)) == -1) {
        if (errno == EINTR)
            printf("timeout reached: no data read from input\n");
        else
            err(EXIT_FAILURE, "read()");
    } else if (n == 0)
        printf("EOF - no more data\n");
    else {
        buf[n] = '\0';
        printf("%s", buf);
    }

    exit(EXIT_SUCCESS);
}

void
handler(int sig, siginfo_t *siginfo, void *ucontext)
{
}
