
/*
 * RUN.C
 *
 * (c)1986 Matthew Dillon     9 October 1986
 *
 *    RUN   handles running of external commands.
 *
 * version 2.04M (Manx ver) by Steve Drew 9-Dec-86
 *
 */

#include "shell.h"

char *FindIt();

do_run(str)
char *str;
{
   int i;
   char buf[128];
   char *path;

   if ((path = FindIt(av[0],"",buf)) && fexecv(path, av) >= 0) {   
      i = wait();
   } else {
      long lock;
      char *copy;

      if ((path = FindIt(av[0],".sh",buf)) == NULL) {
         fprintf(stderr,"Command Not Found %s\n",av[0]);
         return (-1);
      }
      av[1] = buf;               /* particular to do_source() */
      copy = malloc(strlen(str)+3);
      strcpy(copy+2,str);
      copy[0] = 'x';
      copy[1] = ' ';
      i = do_source(copy);
      free(copy);
   }
   return (i);
}


char *
FindIt(cmd, ext, buf)
char *cmd;
char *ext;
char *buf;
{
   long lock = 0;
   char hasprefix = 0;
   APTR original;
   char *ptr, *s = NULL;

   original = Myprocess->pr_WindowPtr;

   for (ptr = cmd; *ptr; ++ptr) {
      if (*ptr == '/' || *ptr == ':')
         hasprefix = 1;
   }
   
   if (!hasprefix) {
   	Myprocess->pr_WindowPtr = (APTR)(-1);
   	s = get_var(LEVEL_SET, V_PATH);
   }

   strcpy(buf, cmd);
   strcat(buf, ext);
   while ((lock = (long)Lock(buf, ACCESS_READ)) == 0) {
      if (*s == NULL || hasprefix) break;
      for(ptr = s; *s && *s != ','; s++) ;
      strcpy(buf, ptr);
      buf[s-ptr] = '\0';
      strcat(buf, cmd);
      strcat(buf, ext);
      if (*s) s++;
   }
   Myprocess->pr_WindowPtr = original;
   if (lock) {
      UnLock(lock);
      return(buf);
   }
   return(NULL);
}


