# include "dvoshell.h"
# include <glob.h>
# define DVO_MAX_PATH 1024

// functions to manage the remote hosts
int hosts (int argc, char **argv) {
  
  if (argc < 2) {
    gprint (GP_ERR, "USAGE: hosts (command) [options]\n");
    gprint (GP_ERR, "  commands:\n");
    gprint (GP_ERR, "    purge-temp : delete all tempfiles for this shell\n");
    return FALSE;
  }

  if (!strncmp(argv[1], "purge-temp", MAX(strlen(argv[1]), 3))) {
    glob_t pglob;
    int PID = getpid();
    int N;
    if ((N = get_argument (argc, argv, "-old-pid"))) {
      remove_argument (N, &argc, argv);
      PID = atoi(argv[N]);
      remove_argument (N, &argc, argv);
    }
    
    int VERBOSE = FALSE;
    if ((N = get_argument (argc, argv, "-v"))) {
      remove_argument (N, &argc, argv);
      VERBOSE = TRUE;
    }
    if ((N = get_argument (argc, argv, "-verbose"))) {
      remove_argument (N, &argc, argv);
      VERBOSE = TRUE;
    }
    
    int DRYRUN = TRUE;
    if ((N = get_argument (argc, argv, "-commit"))) {
      remove_argument (N, &argc, argv);
      DRYRUN = FALSE;
    }
    
    // XXX wrap this up in a function:
    char *CATDIR = GetCATDIR();
    if (!CATDIR) {
      gprint (GP_ERR, "CATDIR is not set\n");
      return FALSE;
    }
    SkyTable *sky = GetSkyTable();
    if (!sky) {
      gprint (GP_ERR, "failed to load sky table for database\n");
      return FALSE;
    }
    HostTable *table = HostTableLoad (CATDIR, sky->hosts);
    if (!table) {
      gprint (GP_ERR, "ERROR: failure reading Host Table %s for database %s\n", sky->hosts, CATDIR);
      return FALSE;
    }    
    
    int i;
    for (i = 0; i < table->Nhosts; i++) {
      pglob.gl_offs = 0;
      char name[DVO_MAX_PATH];
      snprintf (name, DVO_MAX_PATH, "%s/dvo.results.%05d.*.fits", table->hosts[i].pathname, PID);
      if (VERBOSE) gprint (GP_ERR, "checking %s\n", name);
      glob (name, 0, NULL, &pglob);
      int j;
      for (j = 0; j < pglob.gl_pathc; j++) {
	if (VERBOSE) gprint (GP_ERR, "unlink %s\n", pglob.gl_pathv[j]);
	if (!DRYRUN) unlink (pglob.gl_pathv[j]);
      }
      globfree (&pglob);
    }
    return TRUE;
  }

  if (!strncmp(argv[1], "get.results", MAX(strlen(argv[1]), 3))) {
    int N;

    char *varname = NULL;
    if ((N = get_argument (argc, argv, "-var"))) {
      remove_argument (N, &argc, argv);
      varname = strcreate(argv[N]);
      remove_argument (N, &argc, argv);
    }

    if (argc < 2) {
      gprint (GP_ERR, "USAGE: hosts get.results [-var var]\n");
      return FALSE;
    }

    if (varname) {
      set_str_variable (varname, RESULT_FILE);
      free (varname);
    } else {
      gprint (GP_LOG, "results: %s\n", RESULT_FILE);
    }
    return TRUE; 
  }

  

  gprint (GP_ERR, "error: unknown hosts command %s\n", argv[1]);
  return FALSE;
}
