#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 &out, Global &global) : Tag(in, out, global) {
      if(hasContainer)
	throw coreutils::Exception("call cannot have a container.");	
      if(!variableDefined(coreutils::ZString("pgm")))
	throw coreutils::Exception("pgm keyword must be specified.");
      argv[0] = variables["pgm"].c_str(); // TODO: Need to peel off the program name only and pass as argv[0].	   
      for(ix = 1; ix <= 50; ++ix) {    
	 coreutils::MString arg("arg");
	 arg << ix;
	 if(variableDefined(arg))
	   argv[ix] = variables[arg].c_str();
	 else
	   break;
      }
      argv[ix] == NULL;      
      pipe(fdo);
      pid = fork();
      if(pid == 0) {
	 close(fdo[0]);
	 dup2(fdo[1], 1);
	 if(variableDefined("input")) {
	    coreutils::ZString input(variables[variables["input"]]);
	    pipe(fdi);
	    if(fork() == 0) {
	       close(fdi[0]);
	       write(fdi[1], input.getData(), input.getLength());
	       close(fdi[1]);
	       exit(0);
	    }
	    close(fdi[0]);
	    dup2(fdi[0], 0);
	 }
	 rc = execve(variables["pgm"].c_str(), argv, NULL);
	 close(fdo[1]);
	 std::cout << "rc: " << rc << std::endl;
	 exit(rc);
      }
      close(fdo[1]);
      if(variableDefined("name")) 
	global.variables[variables["name"]].read(fdo[0]); 	 
      else 
	out.read(fdo[0]);               
      waitpid(pid, &status, 0);
      std::cout << "status: " << status << std::endl;
   }
   
}
