static char *sccsid = "%Z% %M% %I%    %G% %U%";
/*
*
* findpath - find a command in a path
*     path - list directories searched in path
*
* usage: findpath command(s)
*            path
*
* Written by Ed Carp
*
*/
#include <stdio.h>
#ifndef BSD
#include <string.h>
#else
#include <strings.h>
#endif
#include <sys/types.h>
#ifdef hpux || M_XENIX
#include <sys/ndir.h>
#define dirent direct
#else
#include <dirent.h>
#endif
#include "basename.fun"
#include "strrep.fun"

#define CHARS "*[].^$-+{}()"

char *getenv(), *regcmp(), *regex();

#ifndef HAVE_REGEX
#define regcmp(a, b) re_comp(a)
#define regex(a, b) re_exec(b)
char *re_comp ();
#endif

main(argc, argv)
int argc;
char **argv;
{
   DIR *d;
   struct dirent *dire;
   char *dir, *ptr, *ptr2, path[512], home[64], scr[512];
   char *re;
   int i=1, vflag=0, pflag=0, rflag=0;

   if(strcmp("path", basename(argv[0])) == 0)
   {
      pflag = 1;
      vflag = 1;
   }
   if(argc < 2 && pflag == 0)
   {
      fprintf(stderr, "usage: findpath command(s)...\n");
      exit(1);
   }
   if((dir=getenv("path")) == (char *)NULL)
   {
      if((dir=getenv("PATH")) == (char *)NULL)
      {
         fprintf(stderr, "PATH not set!\n");
         exit(1);
      }
   }
   /* expand ~ in path to $HOME */
   strcpy(home, getenv("HOME"));
   if(home != (char *)EOF)
   {
      while((ptr=strrep("~", home, dir)) != (char *)EOF)
      {
         strcpy(dir, ptr);
      }
   }
   strcpy(path, dir); /* save it away */
   ptr = path;
   if(strpbrk(argv[i], CHARS) != (char *)NULL) rflag = 1;
   /* printf("DEBUG: rflag = %d\n", rflag); */
   /* printf("DEBUG: argv[i] = %s\n", argv[i]); */
   strcpy(scr, "^");
   strcat(scr, argv[i]);
   /* printf("DEBUG: scr = %s\n", scr); */
   if(rflag)
   {
      if((char *)NULL == (re = regcmp(scr, 0)))
      {
         puts("regcmp: Incorrect argument!");
         exit(1);
      }
   }
   while((dir=strtok(ptr, ":")) != (char *)NULL)
   {
      ptr = NULL;
      if(!pflag)
      {
         if((d=opendir(dir)) == (DIR *)NULL)
         {
            perror(dir);
            continue;
         }
      }
      if(vflag) printf("%s\n", dir);
      if(!pflag)
      {
         while((dire=readdir(d)) != (struct dirent *)NULL)
         {
            if(rflag)
            {
               if((ptr2=regex(re, dire->d_name)) != (char *)NULL)
                  printf("%s/%s\n", dir, dire->d_name);
            }
            else
               if(strcmp(dire->d_name, argv[i]) == 0)
                  printf("%s/%s\n", dir, dire->d_name);
         }
      }
      closedir(d);
   }
   if(rflag)
      free(re);
}
