#include "global.h"
#ifdef FIFOSERVER
#include "commands.h"
#include "files.h"
#include <fcntl.h>
#include "hardware.h"
#include "socket.h"

#ifndef O_SYNC
#define O_SYNC 0
#endif

int FIFOout = -1;
static int FIFOin = -1;
static int FIFOctl;
static int FIFOtrace;


extern int mkfifo (const char *__path, mode_t __mode);
extern struct cmds Cmds[];



/* Start up FIFO server */
int
fifo1 (int argc, char *argv[], void *p OPTIONAL)
{
char buf[1024];
int oldin, oldout;
char *bptr;
int offset = 0;
char ch;

	if (argc > 1 && !strnicmp (argv[1], "trace", strlen(argv[1])))
		FIFOtrace = 1;
	else
		FIFOtrace = 0;

	if (FIFOin != -1)	{
		tprintf ("FIFO active: tracing o%s\n", (FIFOtrace) ? "n" : "ff");
		return 0;
	}
	
	(void) mkfifo (FIFO_IN, 0666);
	if ((FIFOin = open (FIFO_IN, O_RDWR)) == -1)	{
		tputs ("Can't open input FIFO");
		return -1;
	}
	(void) mkfifo (FIFO_OUT, 0666);
	if ((FIFOout = open (FIFO_OUT, O_RDWR | O_SYNC)) == -1)	{
		tputs ("Can't open output FIFO");
		close (FIFOin);
		FIFOin = -1;
		return -1;
	}

	if (FIFOtrace)
		tcmdprintf ("FIFO: started\n");
	log (-1, "FIFO: started");

	oldout = Curproc->output;
	oldin = Curproc->input;
	Curproc->output = FIFOout;
	Curproc->input = FIFOin;

	register_io (FIFOin, &FIFOctl);
	while (FIFOin != -1)	{		
		if (kwait (&FIFOctl) != 0)
			continue;

		if (FIFOin == -1)
			break;
		(void) read (FIFOin, &ch, 1);
		buf[offset++] = ch;
		if (ch != '\n')
			continue;

		buf[offset] = 0;
		offset = 0;
		if (FIFOtrace)
			tcmdprintf ("FIFO: %s", buf);
		log (-1, "FIFO: %s", buf);

		bptr = _variable_expansion (strdup (buf));
		(void) cmdparse (Cmds, bptr, NULL);
		write (FIFOout, "\nnet>\n", 6);
		free (bptr);
	}
	if (FIFOtrace)
		tcmdprintf ("FIFO: stopped\n");
	log (-1, "FIFO: stopped");

	Curproc->output = oldout;
	Curproc->input = oldin;
	unlink (FIFO_IN);
	unlink (FIFO_OUT);
	return 0;
}

/* Stop FIFO server */
int
fifo0 (int argc OPTIONAL, char *argv[] OPTIONAL, void *p OPTIONAL)
{
	if (FIFOin != -1)	{
		unregister_io (FIFOin);
		close (FIFOin);
		close (FIFOout);
		FIFOin = -1;
		FIFOout = -1;
		ksignal (&FIFOctl, 1);
	}
	return 0;
}

#endif

