/**************************************************************/
  /*                                                            */
  /*      UNIX 1 / WS 92/93       Gruppe  ux803                 */
  /*      4. Uebung - Aufgabe 3 - builtin.c                     */
  /*                                                            */
  /*      Vorname     Name        Matrikelnr.                   */
  /*     ---------   -------     -------------                  */
  /*      Dietmar     Dierks        125761                      */
  /*      Roman       Czyborra      127221                      */
  /*      Torsten     Buller        117894                      */
  /*      Gerasimos   Paliatsaras   140956                      */
  /*                                                            */
  /**************************************************************/

#define EXIT    1
#define CHDIR   2
#define PWD     3
#define LISTALL 4
#define MENU    5
#define DONE  1
#define NONE  0
#include <stdio.h>     /* stderr, NULL */

static struct map 
{
  char * name;
  int function;
}
builtins [] = 
{
  {"exit", EXIT},
  {"quit", EXIT},
  {"cd",   CHDIR},
  {"pwd",  PWD},
  {"la",   LISTALL},
  {"help", MENU},
  {"menu", MENU},
  {NULL, NONE}
};

extern void do_ls(/* kp */);


#include "parser.h"    /* struct kommando */
#include <sys/param.h> /* MAXPATHLEN */
#include <pwd.h>       /* pw_dir */
#include <stdlib.h>    /* getenv */

int do_builtin (kp)
     struct kommando * kp;

{
  static struct map * mp;
  static char *home, buf [MAXPATHLEN];

  if (!kp-> num_tok1)
    return DONE;

  mp = builtins;
  while (mp->name && strcmp (mp->name, (kp->token_1)[0]))
    ++mp;

  switch (mp -> function)
    {
    case EXIT:
      exit (0);
    case CHDIR:
      if (kp->num_tok1 > 1) {
	if (chdir ((kp->token_1)[1]) == -1)
	  perror ((kp->token_1)[1]);
      } 
      else {
	home = getenv ("HOME");
	if (!home)
	  home = getpwuid (getuid ()) -> pw_dir;
	  chdir (home);
      }
      /* flow through */
    case PWD:
      printf ("cwd=%s\n", getwd (buf));
      return DONE;
    case LISTALL:
      do_ls (kp);
      return DONE;
    case MENU:
      printf ("help menu of msh builtin functions:\n");
      for (mp = builtins; mp->name; ++mp)
	printf ("%s\n", mp->name);
      return DONE;
    case NONE:
      return NONE;
    default:
      fprintf (stderr, "error in builtin's map!\n");
      return DONE;
    }
}