@pragma entry main
@pragma implicit off

@include "tap.inc";

function are_files_identical(a, b)
{
	@local f1, f2, x, y, diff;

	f1 = sys::open(a, sys::O_RDONLY);
	if (f1 <= -1)
	{
		printf("ERROR: unable to open %s\n", a);
		return -1;
	}

	f2 = sys::open(b, sys::O_RDONLY);
	if (f2 <= -1)
	{
		sys::close (a);
		printf("ERROR: unable to open %s\n", b);
		return -1;
	}

	diff = 0;
	while (sys::read(f1, x, 1) > 0)
	{
		if (sys::read(f2, y, 1) <= 0 || x !== y)
		{
			diff = 1;
			break;
		}
	}

	if (sys::read(f2, y, 1) > 0) diff = 1;

	sys::close(f2);
	sys::close(f1);
	return !diff;
}

function run_test (x, more_opts, in_name, set_out_name, out_name)
{
	@local cmd, inf, expf, outf, same;

	if (hawk::isnil(in_name)) in_name = x;
	if (hawk::isnil(out_name)) out_name = x;

	inf = sprintf("%s/%s.in", TDIR, in_name);
	expf = sprintf("%s/%s.out", TDIR, out_name);
	outf = sprintf("/tmp/%s.%d.out", out_name, sys::getpid());
##print TDIR, inf, expf, outf;

	if (set_out_name)
	{
		cmd=sprintf("%s %s -vT_OUT_NAME=%s -f %s/%s.hawk --modlibdirs=%s %s", ARGV[0], more_opts, outf, TDIR, x, hawk::modlibdirs(), inf);
	}
	else
	{
		cmd=sprintf("%s %s -f %s/%s.hawk --modlibdirs=%s %s > %s", ARGV[0], more_opts, TDIR, x, hawk::modlibdirs(), inf, outf);
	}
##print cmd;
	system(cmd);

	same = are_files_identical(expf, outf);
	if (same <= 0)
	{
		## don't delete the output file for review.
		tap_fail(sprintf("%s[%d] %s - %s and %s differ", @SCRIPTNAME, @SCRIPTLINE, x, expf, outf));
	}
	else
	{
		tap_ok(sprintf("%s[%d]", @SCRIPTNAME, @SCRIPTLINE));
		sys::unlink(outf);
	}
}

function run_github_step_JSON_awk() {
	@local url, tgt, tgt_hawk;
	url = "https://raw.githubusercontent.com/step-/JSON.awk/refs/heads/master/JSON.awk";
	tgt = sprintf("%s.%d", "JSON.awk", sys::getpid());
	tgt_hawk = sprintf("%s/%s.hawk", TDIR, tgt);

	system(sprintf("curl -k -o %s %s", tgt_hawk, url));
	run_test(tgt, "", "JSON.awk", 0, "JSON.awk");
	sys::unlink(tgt_hawk);
}

function main()
{
	run_test("journal-toc", "", @nil, 0, @nil);
	run_test("journal-toc", "-vHTML=1", "journal-toc", 0, "journal-toc-html");
	run_test("bibtex-to-html", "", "journal-toc", 1, "bibtex-to-html");
	run_test("fs-test", "", "fs-test", 0, "fs-test");
	run_test("two-way-pipe", "", @nil, 0, "two-way-pipe");

	run_github_step_JSON_awk();
	tap_end();
}

