# include "basic.h"
# include "scheduler.h"
# define prompt "> "

enum {TASK_NONE, TASK_EMPTY, TASK_COMMENT, TASK_END, TASK_HOST, TASK_COMMAND, TASK_PERIODS, TASK_EXIT, TASK_EXEC};

int task (int argc, char **argv) {

  int N;
  int ThisList, status;
  char *input, *outline;
  Macro *macro;
  Task *task;

  if (N = get_argument (argc, argv, "-list")) {
    remove_argument (N, &argc, argv);
    ListTasks ();
    return (TRUE);
  }

  if (N = get_argument (argc, argv, "-show")) {
    remove_argument (N, &argc, argv);
    ShowTask (argv[N]);
    return (TRUE);
  }

  if (argc != 2) {
    fprintf (stderr, "USAGE: task <name>\n");
    fprintf (stderr, "  (enter commands & task functions; end with the word 'END')\n");
    return (FALSE);
  }

  task = FindTask (argv[1]);
  if (task == NULL) { /**** new task ****/
    task = CreateTask (argv[1]);
  }
  SetCurrentTask (argv[1]);

  /* read in task from appropriate source (keyboard or list) until end */

  /* allowed tokens: command, host, stderr, periods, end */

  ThisList = Nlists;
  while (1) {

    /* get the next line (from correct place) */
    if (ThisList == 0) 
      input = readline (prompt);
    else 
      input = get_next_listentry (ThisList);

    if ((ThisList == 0) && (input == (char *) NULL)) {
      fprintf (stderr, "end task with 'END'\n");
      continue;
    }
    if ((ThisList > 0) && (input == (char *) NULL)) {
      fprintf (stderr, "missing 'END' in task definition\n");
      input = strcreate ("end");
    }

    stripwhite (input);
    switch (TaskHash (input)) {

      case TASK_EMPTY:
      case TASK_COMMENT:
	free (input);
	break;

      case TASK_END:
	free (input);
	return (TRUE);
	break;

      case TASK_HOST:
      case TASK_EXIT:
      case TASK_EXEC:
      case TASK_COMMAND:
      case TASK_PERIODS:
	status = command (input, &outline);
	if (outline != NULL) free (outline);
	/* what to do if command is invalid?
	   if (!status) return (FALSE); */
	break;

      case TASK_NONE:
	fprintf (stderr, "unknown task command %s\n", input);
	break;
    }
  }
  return (TRUE);
}

int TaskHash (char *input) {
  
  int hash;
  char *command;

  hash = TASK_NONE;

  command = thisword (input);
  if (command == NULL) return (TASK_EMPTY);

  if (command[0] == '#')                  hash = TASK_COMMENT;
  if (!strcasecmp (command, "END"))       hash = TASK_END;
  if (!strcasecmp (command, "HOST"))      hash = TASK_HOST;
  if (!strcasecmp (command, "COMMAND"))   hash = TASK_COMMAND;
  if (!strcasecmp (command, "PERIODS"))   hash = TASK_PERIODS;
  if (!strcasecmp (command, "TASK.EXIT")) hash = TASK_EXIT;
  if (!strcasecmp (command, "TASK.EXEC")) hash = TASK_EXEC;

  free (command);
  return (hash);
}
