#ifdef __linux__
#include <sys/prctl.h>
#endif
#include <sys/time.h>
#include <sys/wait.h>

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

#include "util.h"

static volatile sig_atomic_t interrupted;

static void
interrupt(int sig)
{
	(void)sig;
	interrupted++;
}

static double
seconds(void)
{
	struct timespec ts;

	assert(clock_gettime(CLOCK_MONOTONIC, &ts) == 0);
	return ts.tv_sec + ts.tv_nsec / 1e9;
}

static int
helper(const char *mode, const char *path)
{
	char buf[4096];
	pid_t child;
	FILE *f;

	if (strcmp(mode, "ok") == 0) {
		printf("abcdef");
		return 0;
	}
	if (strcmp(mode, "fail") == 0)
		return 17;
	if (strcmp(mode, "signal") == 0) {
		raise(SIGTERM);
		return 1;
	}
	if (strcmp(mode, "descendant") == 0 || strcmp(mode, "tree") == 0) {
		assert((child = fork()) != -1);
		if (child == 0) {
			signal(SIGTERM, SIG_IGN);
			for (;;)
				pause();
		}
		printf("%ld", (long)child);
		fflush(stdout);
		if (strcmp(mode, "descendant") == 0)
			return 0;
	}
	if (strcmp(mode, "announce") == 0) {
		assert((f = fopen(path, "w")) != NULL);
		fprintf(f, "%ld", (long)getpid());
		assert(fclose(f) == 0);
	}
	if (strcmp(mode, "empty") == 0)
		close(STDOUT_FILENO);
	if (strcmp(mode, "flood") == 0) {
		memset(buf, 'x', sizeof(buf));
		while (write(STDOUT_FILENO, buf, sizeof(buf)) > 0)
			;
		return 1;
	}
	for (;;)
		pause();
}

#ifdef __linux__
static void
reaped(pid_t pid)
{
	int status;
	double start = seconds();
	struct timespec delay = { 0, 1000000 };

	for (;;) {
		pid_t result = waitpid(pid, &status, WNOHANG);
		if (result == pid) {
			assert(WIFSIGNALED(status) && WTERMSIG(status) == SIGKILL);
			return;
		}
		assert(result == 0 || (result == -1 && errno == EINTR));
		assert(seconds() - start < 2);
		nanosleep(&delay, NULL);
	}
}
#endif

int
main(int argc, char **argv)
{
	char out[32], one = '!', path[] = "/tmp/signet-command.XXXXXX";
	char *cmd[] = { argv[0], "ok", path, NULL };
	char *missing[] = { "/no/such/signet-command", NULL };
#ifdef __linux__
	int fd;
	pid_t caller, child = 0;
	struct timespec delay = { 0, 1000000 };
#endif
	struct sigaction sa, oldsa;
	sigset_t original, current, blocked;
	struct itimerval timer = { { 0, 10000 }, { 0, 10000 } };
	double start;
	int i;
	const char *modes[] = { "hold", "empty", "flood", "tree" };

	if (argc > 1)
		return helper(argv[1], argc > 2 ? argv[2] : NULL);
#ifdef __linux__
	/* Own orphan test descendants so assertions do not rely on container PID1. */
	assert(prctl(PR_SET_CHILD_SUBREAPER, 1) == 0);
#endif
	assert(sigprocmask(SIG_SETMASK, NULL, &original) == 0);
	sigemptyset(&blocked);
	sigaddset(&blocked, SIGCHLD);
	assert(sigprocmask(SIG_BLOCK, &blocked, NULL) == 0);
	assert(run_cmd(cmd, out, 4) == 0 && strcmp(out, "abc") == 0);
	assert(sigprocmask(SIG_SETMASK, NULL, &current) == 0);
	assert(sigismember(&current, SIGCHLD) == 1);
	assert(sigprocmask(SIG_SETMASK, &original, NULL) == 0);
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = SIG_IGN;
	sigemptyset(&sa.sa_mask);
	assert(sigaction(SIGCHLD, &sa, &oldsa) == 0);
	assert(run_cmd(cmd, out, sizeof(out)) == -1 && errno == ECHILD);
	assert(sigaction(SIGCHLD, &oldsa, NULL) == 0);
	assert(run_cmd(cmd, &one, 1) == 0 && one == '\0');
	assert(run_cmd(cmd, out, 0) == -1 && errno == EINVAL);
	cmd[1] = "fail";
	assert(run_cmd(cmd, NULL, 0) == -1 && errno == EIO);
	cmd[1] = "signal";
	assert(run_cmd(cmd, NULL, 0) == -1 && errno == EIO);
	assert(run_cmd(missing, out, sizeof(out)) == -1 && errno == EIO);
	for (i = 0; i < 4; i++) {
		cmd[1] = (char *)modes[i];
		start = seconds();
		assert(run_cmd(cmd, out, sizeof(out)) == -1 && errno == ETIMEDOUT);
		assert(seconds() - start < 2);
#ifdef __linux__
		if (strcmp(modes[i], "tree") == 0)
			reaped((pid_t)strtol(out, NULL, 10));
#endif
	}
	cmd[1] = "descendant";
	assert(run_cmd(cmd, out, sizeof(out)) == 0);
#ifdef __linux__
	reaped((pid_t)strtol(out, NULL, 10));
#endif
	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = interrupt;
	sigemptyset(&sa.sa_mask);
	assert(sigaction(SIGALRM, &sa, NULL) == 0);
	assert(setitimer(ITIMER_REAL, &timer, NULL) == 0);
	cmd[1] = "hold";
	start = seconds();
	assert(run_cmd(cmd, NULL, 0) == -1 && errno == ETIMEDOUT);
	assert(seconds() - start < 2 && interrupted > 0);
	memset(&timer, 0, sizeof(timer));
	assert(setitimer(ITIMER_REAL, &timer, NULL) == 0);
#ifdef __linux__
	fd = mkstemp(path);
	assert(fd != -1);
	close(fd);
	assert((caller = fork()) != -1);
	if (caller == 0) {
		cmd[1] = "announce";
		run_cmd(cmd, NULL, 0);
		_exit(1);
	}
	start = seconds();
	while (!child) {
		FILE *f = fopen(path, "r");
		long value = 0;
		assert(f != NULL);
		if (fscanf(f, "%ld", &value) == 1)
			child = (pid_t)value;
		fclose(f);
		assert(seconds() - start < 2);
		nanosleep(&delay, NULL);
	}
	assert(kill(caller, SIGKILL) == 0);
	reaped(caller);
	reaped(child);
	unlink(path);
#endif
	assert(sigprocmask(SIG_SETMASK, NULL, &current) == 0);
	assert(sigismember(&current, SIGCHLD) == sigismember(&original, SIGCHLD));
	puts("command contract: all passed");
	return 0;
}
