# include "pcontrol.h"
# define DEBUG 0

int CheckDoneHost (Host *host) {
  
  int       status;
  char     *p;
  IOBuffer  buffer;

  ASSERT (host, "host not set");

  InitIOBuffer (&buffer, 0x100);
  
  status = PclientCommand (host, "reset", PCLIENT_PROMPT, &buffer);

  /* check on success of pclient command */
  switch (status) {
    case PCLIENT_DOWN:
      if (DEBUG || VerboseMode()) gprint (GP_ERR, "host %s is down\n", host[0].hostname);
      /* DONE host does not have an incomplete job */
      HarvestHost (host[0].pid);
      PutHost (host, PCONTROL_HOST_DOWN, STACK_BOTTOM);
      FreeIOBuffer (&buffer);
      return (FALSE);
      // XXX do we need to close the connection?

    case PCLIENT_HUNG:
      // don't do anything drastic, just try again later
      PutHost (host, PCONTROL_HOST_DONE, STACK_BOTTOM);
      if (DEBUG || VerboseMode()) gprint (GP_ERR, "host %s is not responding\n", host[0].hostname);
      FreeIOBuffer (&buffer);
      return (FALSE);

    case PCLIENT_GOOD:
      if (VerboseMode()) gprint (GP_ERR, "message received (CheckDoneHost)\n");  
      break;

    default:
      ABORT ("unknown status for pclient command");  
  }

  /** successful command, examine result **/
  p = memstr (buffer.buffer, "STATUS", buffer.Nbuffer);
  ASSERT (p != NULL, "missing STATUS in pclient message (CheckDoneHost)");

  sscanf (p, "%*s %d", &status);
  switch (status) {
    case -1:
      ABORT ("reset syntax error");
      
    case 0:
      if (DEBUG || VerboseMode()) gprint (GP_ERR, "reset failed\n");
      PutHost (host, PCONTROL_HOST_DONE, STACK_BOTTOM);
      FreeIOBuffer (&buffer);
      return (FALSE);
      
    case 1:
    case 2:
      if (DEBUG || VerboseMode()) gprint (GP_ERR, "successful reset\n");
      PutHost (host, PCONTROL_HOST_IDLE, STACK_BOTTOM);
      FreeIOBuffer (&buffer);
      return (FALSE);

    default:
      ABORT ("should not reach here (CheckDoneHost)");
  }
  ABORT ("should not reach here (CheckDoneHost)");
}

/** probably need to flush the buffer before the command **/
/** need to add timeout check here **/
