// SPDX-FileCopyrightText: 2019 Badwolf Authors <https://hacktivis.me/projects/badwolf>
// SPDX-License-Identifier: BSD-3-Clause

#include "badwolf.h"
#include "config.h"

void
man_uri_scheme_request_cb(WebKitURISchemeRequest *request, gpointer user_data)
{
	const char *req_path = webkit_uri_scheme_request_get_path(request);

	if(req_path == NULL || req_path[0] == 0) req_path = "man";

	char *path = strdup(req_path);

	char *man_ref[2] = {path, NULL};

	char *sep = strrchr(path, '.');
	if(sep)
	{
		sep[0]     = 0;
		man_ref[0] = sep + 1;
		man_ref[1] = path;
	}

	GSubprocessFlags flags_subproc = G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_MERGE;

	GError *error_proc    = NULL;
	GSubprocess *man_proc = g_subprocess_new(
	    flags_subproc, &error_proc, BADWOLF_MAN_HTML_CMD, man_ref[0], man_ref[1], NULL);
	if(error_proc != NULL)
	{
		webkit_uri_scheme_request_finish_error(request, error_proc);
		free(path);
		return;
	}

	GInputStream *stream = g_subprocess_get_stdout_pipe(man_proc);

	// Pipe the contents out, can't wait beforehand as the buffer needs to drain on large manpages
	webkit_uri_scheme_request_finish(request, stream, -1, "text/html");

	free(path);
	g_object_unref(stream);
}
