# include "pcontrol.h"
# define PCLIENT_TIMEOUT 500

int PclientCommand (Host *host, char *command, char *response, IOBuffer *buffer) {

  int i;
  int status;
  char *line;
  struct timespec request, remain;

  ASSERT (host != NULL, "host missing");
  ASSERT (buffer != NULL, "buffer missing");
  ASSERT (command != NULL, "command missing");
  ASSERT (response != NULL, "response missing");

  /* avoid blocking on read, test every 100 usec, up to 50 msec */
  request.tv_sec = 0;
  request.tv_nsec = 100000;

  // flush the stdout and stderr buffers here
  ReadtoIOBuffer (buffer, host[0].stdout_fd);
  FlushIOBuffer (buffer);
  ReadtoIOBuffer (buffer, host[0].stderr_fd);
  FlushIOBuffer (buffer);

  /* send command to client (adding on \n) */
  status = write_fmt (host[0].stdin_fd, "%s\n", command);

  /* is pipe still open? */
  if ((status == -1) && (errno == EPIPE)) {
    // gprint (GP_ERR, "pclient read gives pipe error for %s\n", command);
    return (PCLIENT_DOWN);
  }
  
  /* watch for response - wait up to 1 second */
  line = NULL;
  status = -1;
  for (i = 0; (i < PCLIENT_TIMEOUT) && (status != 0) && (line == NULL); i++) {
    status = ReadtoIOBuffer (buffer, host[0].stdout_fd);
    line = memstr (buffer[0].buffer, response, buffer[0].Nbuffer);
    if (status == -1) nanosleep (&request, &remain);
  }
  if (status ==  0) {
    // gprint (GP_ERR, "pclient read returns 0 for %s\n", command);
    return (PCLIENT_DOWN);
  }
  if (status == -1) return (PCLIENT_HUNG);
  /* gprint (GP_ERR, "buffer.buffer: %s\n", buffer[0].buffer); */
  return (PCLIENT_GOOD);
}

/* memstr returns a view, not an allocated string : don't free */
