#include "__system.h"
#include "Exception.h"
#include "MString.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

namespace jet {
   
   __system::__system(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
      if(hasContainer)
	throw coreutils::Exception("system tag cannot have a container.");	
      if(!keywordDefined(coreutils::ZString("cmd")))
	throw coreutils::Exception("cmd keyword must be specified.");
      pipe(fdo);
      pid = fork();
      if(pid == 0) {
	 close(fdo[0]);
	 dup2(fdo[1], 1);
	 if(keywordDefined("input")) {
	    resolveKeyword("input");
	    coreutils::ZString input(keywords[resolveKeyword("input")]);
	    pipe(fdi);
	    if(fork() == 0) {
	       close(fdi[0]);
	       write(fdi[1], input.getData(), input.getLength());
	       close(fdi[1]);
	       exit(0);
	    }
	    close(fdi[1]);
	    dup2(fdi[0], 0);
	 }
	 system(keywords[resolveKeyword("cmd")].c_str());
	 close(fdo[1]);
	 exit(errno);
      }
      close(fdo[1]);
      if(keywordDefined("name")) 
	global.variables[keywords[resolveKeyword("name")]].read(fdo[0]); 	 
      else 
	out.read(fdo[0]);               
      waitpid(pid, &status, 0);
   }
   
}
