#include <stdio.h>
#include <libmawk.h>

/*
	Purpose: wire stdout to a pipe and process the output of the script and
	         hijack output file "log". Manual setup.
	Run: ./app -f test.awk
*/

void print_pipe_pending(mawk_state_t *m, mawk_vio_t *vf, char *sep)
{
	for(;;) {
		int len;
		char buf[1024];
		len = mawk_vio_fifo_read_app(m, vf, buf, sizeof(buf)-1);
		if (len <= 0)
			return;
		buf[len] = '\0';
		printf("<%s>\n%s</%s>\n", sep, buf, sep);
	}
}

int main(int argc, char **argv)
{
	mawk_state_t *m;
	mawk_vio_t *vf_stdin, *vf_stdout, *vf_log;

	/* init a context in stages */
	m = libmawk_initialize_stage1();              /* alloc context */

	/* set up all pipes */
	mawk_vio_orig_setup_stdio(m, 0, 0, 1); /* whether bind to the app's stdio: 0,0,1=stdin,stdout,stderr; let stderr bind */
	vf_stdin  = mawk_vio_fifo_open(m, NULL, MAWK_VIO_I);        /* create a pipe for stdin */
	vf_stdout = mawk_vio_fifo_open(m, NULL, MAWK_VIO_O_APPEND); /* create a pipe for stdout */
	vf_log    = mawk_vio_fifo_open(m, NULL, MAWK_VIO_O_APPEND); /* create a pipe for logging */
	mawk_file_register(m, "/dev/stdin",  F_IN,  vf_stdin);      /* register /dev/stdin */
	mawk_file_register(m, "/dev/stdout", F_APPEND, vf_stdout);  /* register /dev/stdout */
	mawk_file_register(m, "log",         F_APPEND, vf_log);     /* register a regular open file named "log" */
	m->vio_init = mawk_vio_orig_init; /* file operation is handled by the orig vio */

	m = libmawk_initialize_stage2(m, argc, argv); /* set up with CLI arguments */
	m = libmawk_initialize_stage3(m);             /* execute BEGIN */

	if (m == NULL) {
		fprintf(stderr, "libmawk_initialize failed, exiting\n");
		return 1;
	}

	/* libmawk_append_input() operates on "/dev/stdin" as registered, if it is
	   a pipe, so it is compatible with manual setup */
	libmawk_append_input(m, "Hello world!\n");
	libmawk_run_main(m);


	/* print all the stdout the script produced so far */
	print_pipe_pending(m, vf_stdout, "stdout");
	print_pipe_pending(m, vf_log,    "log");

	/* run END and free the context */
	libmawk_uninitialize(m);

	return 0;
}

