/*
 * Copyright (c) 2004-2005 HEAnet ltd. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the HEAnet Ltd. nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Sexec - Colm.MacCarthaigh@heanet.ie
 * 	   Brian.Boyle@heanet.ie  
 *
 * 	   08/01/2004
 *
 * Colourise and distinguish between stderr and stdout, useful
 * for cronjobs or interactive processes.
 *
 */
#include <sys/select.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

void usage(void)
{	
	fprintf(stderr, 
		"sexec [-x] command [arg ...]\n\n"
		"  -x  output XHTML, default is to output ANSI terminal escape\n"
		"     sequences.\n\n");
	exit(1);
}

int main(int argc, char *argv[])
{
	/* Our various user-definable options */
	static enum { XHTML, ANSI } 		output_type = ANSI;
	static enum { STDOUT, STDERR, NONE }  	latch = NONE;

	/* Other variables */
	int			highest_fd,
				status;
	pid_t			pid;
	fd_set			fdset, copy;

	/* The pipes used for IO */
	int			stdout_pipe[2];
	int			stderr_pipe[2];

	/* See if the first argyment is -x */
	if (argc > 1 && !strcmp(argv[1], "-x"))
	{
		output_type = XHTML;
		argv += 2;
		argc--;
	}
	else
	{
		argv += 1;
	}
	
	/* See if we have been given any further arguments */
	if (argc <= 1)
	{
		usage();
	}

	/* Set up the pipes */
	if (pipe(stdout_pipe) < 0 || pipe(stderr_pipe) < 0)
	{
		fprintf(stderr, "error using pipe()\n");
		exit(1);
	}

	/* We need to fork() a child process */
	switch (pid = fork())
	{
		case -1: /* Error occurred */
			fprintf(stderr, "error using fork()\n");
			exit(1);
			break;

		case 0:	/* This is the child */

			/* Close the ends of the pipes we wont be using */
			close(stdout_pipe[0]);
			close(stderr_pipe[0]);

			/* Attach stdout to the write end of the pipe */
			if (stdout_pipe[1] != STDOUT_FILENO)
			{
				close(STDOUT_FILENO);
				dup2(stdout_pipe[1], STDOUT_FILENO);
				close(stdout_pipe[1]);
			}
	
			/* Attach stderr to the write end of the pipe */
			if (stderr_pipe[1] != STDERR_FILENO)
			{
				close(STDERR_FILENO);
				dup2(stderr_pipe[1], STDERR_FILENO);
				close(stderr_pipe[1]);
			}
		
			/* Execute the target command */
			execvp(*argv, argv);

			/* If we got here, it's an error */
			fprintf(stderr, "error using execvp: %s\n",
					strerror(errno));
			_exit(127);
			break;
	}


	/* This is the parent */

	/* Close the ends of the pipes we wont be using */
	close(stdout_pipe[1]);
	close(stderr_pipe[1]);

	/* We'll have to select() between stdout and stderr */
	FD_ZERO( &fdset );
	FD_SET(stdout_pipe[0], &fdset);
	FD_SET(stderr_pipe[0], &fdset);

	/* Determine the highest file descriptor */
	stdout_pipe[0] > stderr_pipe[0] ?
			(highest_fd = stdout_pipe[0]) :
			(highest_fd = stderr_pipe[0]) ;

	/* 
	 * Turn IO buffering off, we only use *printf for format
	 * specification handiness 
	 */
	setvbuf(stdout, NULL, _IONBF, 0);
	setvbuf(stderr, NULL, _IONBF, 0);
	
	/* We use a copy of fdset, as select modifies it */
	copy = fdset;
	while (select(highest_fd + 1, &copy, NULL, NULL, NULL ) > 0)
	{
		char buffer[10240];
		int  bytes;

		if (FD_ISSET(stdout_pipe[0], &copy))
		{
			if ((bytes = 
			     read(stdout_pipe[0], buffer, sizeof(buffer) - 1)) <= 0)
			{
				/* We've reached EOF */
				break;
			}
			buffer[bytes] = '\0';

			if (output_type == XHTML)
			{
				if (latch != STDOUT)
				{
					if (latch != NONE)
					{
						printf("</div>\n");
					}

					printf("<div class=\"stdout\">%s", buffer);

					latch = STDOUT;
				}
				else
				{
					printf("%s", buffer);
				}
			}
			else
			{
				printf("\033[32;1m%s\033[0m", buffer);
			}
		} 
		else if (FD_ISSET(stderr_pipe[0], &copy))
		{
			if ((bytes = 
			     read(stderr_pipe[0], buffer, sizeof(buffer) - 1)) <= 0)
			{
				/* We've reached EOF */
				break;
			}
			buffer[bytes] = '\0';

			if (output_type == XHTML)
			{
				if (latch != STDERR)
				{
					if (latch != NONE)
					{
						printf("</div>\n");
					}

					printf("<div class=\"stderr\">%s", buffer);

					latch = STDERR;
				}
				else
				{
					printf("%s", buffer);
				}
			}
			else 
			{
				printf("\033[31;1m%s\033[0m", buffer);
			}
		}
		else
		{
			fprintf(stderr, "Error using select\n");
			exit(1);
		}

		/* reset copy */
		copy = fdset;
	}

	if (latch != NONE)
	{
		printf("</div>\n");
	}

	/* Wait for the child to exit */
	waitpid(pid, &status, WUNTRACED);

	return 0;
}

