#include <unistd.h>
#include <stdio.h> 
#include <string.h> 
#include <malloc.h>
#include <stdlib.h>

#include "debug.h"
#include "parse.h"
#include "execute.h"
#include "prompt.h"

#define module_name "interp"

int interactive = 1;
 
int interpreter(FILE *fin) 
{ 
  int args; 
  int err; 
  
  char line[256], *tobefreed = NULL; 
  char* argv[100]; 

  char tmp[256];

  memset(line, 0, 200*sizeof(char));

  prompt_init();

  while (1) 
  {
    prompt();
      
    fgets(line, 256, fin);

    DEBUG("command-line recieved");

    if(tobefreed != NULL)
      free(tobefreed);
    tobefreed = parse(line, &args, argv);

    DEBUG("arguments parsed, command name is:");

    DEBUG(argv[0]);

    if(args == 0);
    else if (!strcmp("exit", argv[0]) || feof(fin))
    {
      DEBUG("Exit command recieved. Exiting.");
      return 0;
    }

    else if (!strcmp("cd", argv[0]))
    {
      command_count++;
      if(args == 1)
        err = chdir("~");
      else
        err = chdir(argv[1]);

      if(err)
        perror("fsh");
    }

    else if (!strcmp("chroot", argv[0]))
    {
      command_count++;
      if(args == 1)
      {
        ERROR("a argument MUST be given to chroot!");
      }
      else
        err = chdir(argv[1]);

      if(err)
        perror("fsh");
    }

    else if (!strcmp("pwd", argv[0]))
    {
      char buff[261];
      command_count++;
      if (getcwd(tmp, 256) != NULL)
        {
          sprintf(buff, "%s", tmp);
          printf("%s\n", buff);
          sprintf(buff, "PWD=%s", tmp);
          putenv(buff);    /* some programs expect PWD to be set */
        }
      else
        perror("fsh");
    }

    else if (!strcmp("set", argv[0]))
    {
      command_count++;
      if (args > 1)
	{
	  char plunk[256];
     	  printf("%s", argv[1]);
          if (!putenv(argv[1]))
            {
              perror("fsh");
	      sprintf(plunk, "%s", argv[1]);
              DEBUG(plunk);
	    }
        }
      else
	{
	  printf("usage: set <name>=<var>\n");
	}
    }

    else if (!strcmp("unset", argv[0]))
    {
      command_count++;
      unsetenv(argv[1]);
    }

    else
    {
      DEBUG("From the main process");	  
      command_count++;
      execute(argv[0], argv, 0);
    }
  }
  
  fflush(stdout);
}

