# include "dvoshell.h"

int catname (int argc, char **argv) {
  
  int i, N;
  struct stat filestat;

  int ShowHost = FALSE;
  if ((N = get_argument (argc, argv, "-host"))) {
    remove_argument (N, &argc, argv);
    ShowHost = TRUE;
  }
  int ShowBackup = FALSE;
  if ((N = get_argument (argc, argv, "-backup"))) {
    remove_argument (N, &argc, argv);
    ShowBackup = TRUE;
  }
  int FullName = FALSE;
  if ((N = get_argument (argc, argv, "-full-name"))) {
    remove_argument (N, &argc, argv);
    FullName = TRUE;
  }
  int ShowFlags = FALSE;
  if ((N = get_argument (argc, argv, "-flags"))) {
    remove_argument (N, &argc, argv);
    ShowFlags = TRUE;
  }
  int PARALLEL = FALSE;
  if ((N = get_argument (argc, argv, "-parallel"))) {
    remove_argument (N, &argc, argv);
    PARALLEL = TRUE;
  }

  if (argc != 2) {
    gprint (GP_ERR, "USAGE: catname name [-host] [-backup] [-flags]\n");
    return (FALSE);
  }

  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;
  }    
  SkyList *skylist = SkyListByName (sky, argv[1]);

  // prepare to handle interrupt signals
  signal (SIGINT, handle_interrupt);
  interrupt = FALSE;

  for (i = 0; (i < skylist[0].Nregions) && !interrupt; i++) {
    char *filename = NULL;
    if (PARALLEL) {
      SkyRegion *region = skylist[0].regions[i];
      int hostID = (region->hostFlags & DATA_USE_BCK) ? region->backupID : region->hostID;
      int index = table->index[hostID];
    
      char hostfile[1024];
      snprintf (hostfile, 1024, "%s/%s.cpt", table->hosts[index].pathname, region->name);
      filename = hostfile;
    } else {
      filename = skylist[0].filename[i];
    }

    gprint (GP_ERR, "%3d %s", i, skylist[0].regions[i][0].name);
    if (stat (filename, &filestat) != -1) {
      gprint (GP_ERR, " +");
    } else {
      gprint (GP_ERR, " -");
    } 
    if (ShowHost) {
      gprint (GP_ERR, "  %3d", skylist[0].regions[i][0].hostID);
    } else {
      gprint (GP_ERR, "     ");
    }
    if (FullName) {
      gprint (GP_ERR, "  %s", filename);
    }
    if (ShowBackup) {
      gprint (GP_ERR, "  %3d", skylist[0].regions[i][0].backupID);
    } else {
      gprint (GP_ERR, "     ");
    }
    if (ShowFlags) {
      gprint (GP_ERR, "  0x%04x", skylist[0].regions[i][0].hostFlags);
    } else {
      gprint (GP_ERR, "        ");
    }
    gprint (GP_ERR, "\n");
    set_str_variable ("CATNAME", filename);
  }

  return (TRUE);
  SkyListFree (skylist);
}
