#include <sys/wait.h>

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

#include "pdfw.h"

/* Only pdfw.c/ttf.c allocations are redirected, never libc or codec internals. */
static void *live[1024];
static size_t calls, fail_at;
static int persistent, failed;

static int
reject(void)
{
	calls++;
	if (fail_at && (calls == fail_at || (persistent && calls > fail_at))) {
		failed = 1;
		return 1;
	}
	return 0;
}

static void
record(void *p)
{
	size_t i;

	if (p == NULL)
		return;
	for (i = 0; i < sizeof(live) / sizeof(live[0]); i++)
		if (live[i] == NULL) {
			live[i] = p;
			return;
		}
	abort();
}

void *
test_malloc(size_t n)
{
	void *p;

	if (reject())
		return NULL;
	p = malloc(n);
	record(p);
	return p;
}

void *
test_calloc(size_t n, size_t size)
{
	void *p;

	if (reject())
		return NULL;
	p = calloc(n, size);
	record(p);
	return p;
}

void *
test_realloc(void *old, size_t n)
{
	void *p;
	size_t i;

	if (reject())
		return NULL;
	if (old == NULL) {
		p = realloc(NULL, n);
		record(p);
		return p;
	}
	for (i = 0; i < sizeof(live) / sizeof(live[0]); i++)
		if (live[i] == old)
			break;
	assert(i < sizeof(live) / sizeof(live[0]));
	p = realloc(old, n);
	if (p != NULL)
		live[i] = p;
	return p;
}

char *
test_strdup(const char *s)
{
	char *p = test_malloc(strlen(s) + 1);

	if (p != NULL)
		strcpy(p, s);
	return p;
}

void
test_free(void *p)
{
	size_t i;

	if (p == NULL)
		return;
	for (i = 0; i < sizeof(live) / sizeof(live[0]); i++)
		if (live[i] == p)
			break;
	assert(i < sizeof(live) / sizeof(live[0]));
	live[i] = NULL;
	free(p);
}

static int
check_leaks(void)
{
	size_t i, n = 0;

	for (i = 0; i < sizeof(live) / sizeof(live[0]); i++)
		if (live[i] != NULL)
			n++;
	if (n)
		fprintf(stderr, "FAIL: %zu writer/font allocations leaked\n", n);
	return n ? 1 : 0;
}

static int
exercise(const char *mode, const char *font_path, const char *image,
    const char *output)
{
	pdfw *p;
	char text[12000];
	int font, rc, image_rc;

	if (strcmp(mode, "open") == 0) {
		fail_at = 2;
		persistent = 1;
	}
	p = pdfw_open(output);
	if (p == NULL)
		return check_leaks();
	if (strcmp(mode, "open") == 0) {
		pdfw_close(p);
		fprintf(stderr, "FAIL: open accepted failed object allocation\n");
		return 1;
	}
	pdfw_page(p, 595, 842);
	if (strcmp(mode, "growth") == 0) {
		pdfw_text(p, PDFW_HELVETICA, 12, 10, 20, "initial buffer");
		fail_at = calls + 1;
	}
	if (strcmp(mode, "font-used") == 0)
		fail_at = calls + 2; /* ttf bytes, then glyph bookkeeping */
	if (strcmp(mode, "font-path") == 0)
		fail_at = calls + 3;
	if (strcmp(mode, "growth") == 0)
		font = PDFW_HELVETICA;
	else
		font = pdfw_font(p, font_path);
	memset(text, 'A', sizeof(text) - 1);
	text[sizeof(text) - 1] = '\0';
	pdfw_text(p, font, 12, 10, 20, text);
	pdfw_clip_circle(p, 100, 100, 20);
	image_rc = pdfw_image(p, image, 80, 80, 40, 40);
	pdfw_clip_end(p);
	pdfw_page(p, 842, 595);
	pdfw_text(p, font, 12, 10, 20, "Second page (text) \\ and Unicode: ₹");
	pdfw_image(p, image, 80, 80, 40, 40);
	rc = pdfw_close(p);
	if (fail_at && !failed) {
		fprintf(stderr, "FAIL: allocation injection not reached\n");
		return 1;
	}
	if ((!fail_at && (rc != 0 || font == PDFW_HELVETICA || image_rc != 0)) ||
	    (failed && (strcmp(mode, "sweep") != 0 ||
	    (font != PDFW_HELVETICA && image_rc == 0)) && rc != -1)) {
		fprintf(stderr, "FAIL: unexpected render/close result %d\n", rc);
		return 1;
	}
	return check_leaks();
}

static int
run_case(const char *mode, const char *font, const char *image,
    const char *output, size_t at, int permanent)
{
	pid_t pid;
	int status;

	fflush(NULL);
	pid = fork();
	assert(pid != -1);
	if (pid == 0) {
		alarm(3);
		calls = 0;
		fail_at = at;
		persistent = permanent;
		exit(exercise(mode, font, image, output));
	}
	assert(waitpid(pid, &status, 0) == pid);
	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		fprintf(stderr, "FAIL: %s allocation=%zu persistent=%d status=%d\n",
		    mode, at, permanent, status);
		return 1;
	}
	return 0;
}

int
main(int argc, char **argv)
{
	const char *modes[] = { "open", "growth", "font-used", "font-path" };
	size_t i, total;
	int errors = 0, permanent;

	assert(argc == 4);
	/* Keep the healthy two-page PDF for independent qpdf validation. */
	if (exercise("healthy", argv[1], argv[2], argv[3]) != 0)
		return 1;
	total = calls;
	for (i = 0; i < sizeof(modes) / sizeof(modes[0]); i++)
		errors += run_case(modes[i], argv[1], argv[2], "/dev/null", 0, 0);
	for (permanent = 0; permanent <= 1; permanent++)
		for (i = 1; i <= total; i++)
			errors += run_case("sweep", argv[1], argv[2], "/dev/null",
			    i, permanent);
	printf("pdfw allocation contract: %zu sites, transient/persistent failures, "
	    "%d failed cases\n", total, errors);
	return errors ? 1 : 0;
}
