#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/poll.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>

#include "orcd.h"

#define BUFSIZE 1024

#define OUTPUT "/tmp/execd.output"

void execd(orcd_t *orcd)
{
  FILE *output=stdout;

  char buf[BUFSIZE];

  int fd=orcd->execpipe[0];

  //Read out any junk sitting in the fifo
  struct pollfd p;
  p.fd = fd;
  p.events = 0;
  p.events |= POLLIN;
  while(poll(&p,1,1000))
    {
      int res=read(fd,buf,1);
      if (res==0)
	break;

      if (read(fd,buf,1)<0)
	{
	  perror("Error while flushing execd.fifo");
	  return;
	}
    }

  //Switch to FILE* operations
  FILE *fp = fdopen(fd,"r");
  if (!fp)
    {
      perror("Unable to obtain FILE*.");
      return;
    }

  FILE *console = fdopen(orcd->consolepipe[1], "w");

  pid_t pid;

  while(fgets(buf,BUFSIZE,fp))
    {
      if (!buf[0])
	continue;
      pid = fork();
      if (pid < 0)
	{
	  perror("Error while forking");
	  return;
	}
      if (!pid)
	{
	  time_t thetime=time(NULL);
	  fprintf(output,"-----------------------------------------\n");
	  fprintf(output,"Launching at %s",ctime(&thetime));
	  fprintf(output,"%s",buf);
	  fprintf(output,"-----------------------------------------\n");
	  fflush(output);

	  FILE *o=popen(buf, "r");
	  
	  while (fgets(buf, 1000, o))
	    {
	      fputs(buf,output);
	      fputs(buf,console);
	    }

	  fclose(o);

	  return;
	}
      waitpid(pid, NULL, 0);
    }
  fclose(fp);
  printf("EOF\n");

}
