#define _GNU_SOURCE

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

static void usage(void);

int
main(int argc, char *argv[])
{
    int status;
    pid_t childPid;

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

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

    case 0:
        printf("child started with PID = %ld\n", (long) getpid());
        if (argc > 1) {
            if ((errno = toInt(argv[1], &status)) != 0)
                err(EXIT_FAILURE, "toInt('%s')", argv[1]);
            exit(status);
        } else {
            for ( ; ; )
                pause();
        }
        exit(EXIT_FAILURE);

    default:
        for ( ; ; ) {
            childPid = waitpid(-1, &status, WUNTRACED
#ifdef WCONTINUED
                                                | WCONTINUED
#endif
                    );
            if (childPid == -1)
                err(EXIT_FAILURE, "waitpid");

            printf("waitpid() returned: PID=%ld; status=0x%04x (%d,%d)\n",
                    (long) childPid,
                    (unsigned int) status, status >> 8, status & 0xff);
            printWaitStatus(NULL, status);

            if (WIFEXITED(status) || WIFSIGNALED(status))
                exit(EXIT_SUCCESS);
        }
    }

    exit(EXIT_SUCCESS);
}

static void
usage(void)
{
    fprintf(stderr, "usage: %s [child-exit-status]\n",
            program_invocation_short_name);
    exit(EXIT_FAILURE);
}
