/*
 * cpl:  A shell pipeline parser.
 *
 * Author: Dr. Phillip Nico
 *             with modifications by Gene Fisher
 *         Department of Computer Science
 *         California Polytechnic State University
 *         One Grand Avenue.
 *         San Luis Obispo, CA  93407  USA
 *
 * Email:  pnico@csc.calpoly.edu
 *         gfisher@calpoly.edu
 *
 * Revision History:
 *         $Log: main.c,v $
 *         Revision 1.4  2003-04-15 18:11:34-07  pnico
 *         Checkpointing before distribution
 *
 *         Revision 1.3  2003-04-12 10:37:22-07  pnico
 *         added config.h to list of inclusions
 *
 *         Revision 1.2  2003-04-11 08:38:55-07  pnico
 *         Ready for first release of mice
 *
 *         Revision 1.1  2003-04-10 19:36:24-07  pnico
 *         Initial revision
 *
 *
 */
#include "config.h"

#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "pipeline.h"
#include "longstr.h"
#include "parser.h"

#define PROMPT "what? "

static void printusage(char *name);
static void prompt(char *prompt);

int main(int argc, char *argv[]){
  char *line;
  pipeline pl;
  int run;
  char *promptstr;

  /* check for the right number of arguments */
  if ( argc > 1 ) {
    printusage(argv[0]);
    exit(-1);
  }

  /* set prompt */
  promptstr = PROMPT;

  run = TRUE;
  prompt(promptstr);
  while ( run ) {
    if ( NULL == (line = readLongString(stdin)) ) {
      if ( feof(stdin) )
        run = FALSE;
    } else {
      /* We got a line, send it off to the pipeline parser. */
      pl = parse_pipeline(line);

      /*
       * Show that it worked.  This is where you're going to do
       * something radically different: rather than printing the
       * pipeline, you're going to execute it.
       */
      if ( pl != NULL ) {
        print_pipeline(stdout,pl); /* print it. */

	/* Stop running if Stage 0 argv[0][0] = 'q'. */
	if ((pl->stage != NULL) &&
	    (pl->stage[0].argv != NULL) &&
            (pl->stage[0].argv[0] != NULL) &&
	    (pl->stage[0].argv[0][0] == 'q')) {
		run = FALSE;
	}
      }
      free_pipeline(pl);          /* also frees line */

      lineno++;  /* readLongString trims newlines, so increment it manually */
    }
    if (run )                 /* assuming we still want to run */
      prompt(promptstr);
  }

  return 0;
}

static void prompt(char *pr) {
  /* If this is an interactive shell, flush the output streams and
   * print a prompt
   */

  if ( isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) ) {
    printf("%s", pr);
    fflush(stdout);
  }
}

static void printusage(char *name){
  fprintf(stderr,"usage: %s\n",name);
}