#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#include <errno.h>
#include <sys/wait.h>
#include "../lpi.h"

void usage(void);

int
main(int argc, char *argv[])
{
    int numDead;
    int secsToSleep;
    pid_t childPid;
    int j;

    if (argc < 2 || strcmp(argv[1], "--help") == 0) {
        usage();
        /* UNREACHABLE */
    }

    setbuf(stdout, NULL);       /* disable buffering of stdout */

    for (j = 1; j < argc; j++) {
        if ((errno = toInt(argv[j], &secsToSleep)) != 0) {
            warn("toInt('%s')", argv[j]);
            continue;
        }

        switch (fork()) {
        case -1:
            err(EXIT_FAILURE, "fork");

        case 0:
            printf("[%s] child %d started with PID %ld, sleeping %s "
                    "seconds\n", currTime("%T"), j, (long) getpid(), argv[j]);
            sleep(secsToSleep);
            _exit(EXIT_SUCCESS);

        default:
            break;
        }
    }

    numDead = 0;
    for ( ; ; ) {
        childPid = wait(NULL);
        if (childPid == -1) {
            if (errno == ECHILD) {
                printf("No more children - bye!\n");
                exit(EXIT_SUCCESS);
            } else {
                err(EXIT_FAILURE, "wait");
            }
        }

        numDead++;
        printf("[%s] wait() returned child PID %ld (numDead=%d)\n",
                currTime("%T"), (long) childPid, numDead);
    }
    exit(EXIT_SUCCESS);
}

void
usage(void)
{
    fprintf(stderr, "usage: %s sleep-time...\n", program_invocation_short_name);
    exit(EXIT_FAILURE);
}
