//
// wild.cpp: new 07-24-23.  Helper functions for directory listings, w/ wild card specifiers.
//
//
//
//
//
//
//





#ifdef NEED_PCH
   #include "pch.h"
#else
   #include "stdafx.h"
#endif // !NEED_PCH


#pragma warning( disable : 4996 )


#include "globs.h"
// #include <sys/utime.h>
#include <stdio.h>
#include <stdlib.h>

// #include <io.h>
#include <time.h>
#include "wild.h"

#ifdef _WIN32
#include <direct.h>
#else
#include <sys/types.h>
#include <dirent.h>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// #define _stat64 stat64
typedef struct dirent DIR_GUY;

#endif // _WIN32

#define MAX_FULL_NAME_LEN     (65536)



// qxl: movement in the upper half of ASCII?
static const unsigned char lwc[] = {
   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,
   0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
   0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,
   0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
   0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
   0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,
   0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,
   0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,
   0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F,
   0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,
   0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,
   0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xD7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,
   0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,
   0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,
   0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
};





////////////////////////////////////////////////////////////////////////////////////////




bool debug = false;
FILE *fp_out = NULL;





#ifdef _WIN32

//
//
//
// 10-01-20: calloc() -> new; free() -> delete.
//
// qxopendir()

DIR     *opendir(const char *dirname) {
   DIR  *dp = NULL;
   unsigned int attrib = (_A_ARCH | _A_HIDDEN | _A_NORMAL | _A_RDONLY | _A_SYSTEM);

   if(debug) {
      qprintf(fp_out, "This is msdev opendir() for %s.\n", dirname);
      fflush(fp_out);
   }

   SMARTA(cp, char, (strlen(dirname) + 32), smaCp);

   if(cp == NULL) {
      qprintf(stdout, "Unable to allocate memory.\n");
      return (NULL);
   }

   if(is_slash(dirname[strlen(dirname)-1])) {
      sprintf(cp, "%s%s", dirname, "*.*");
   } else {
      /* normal directory: no slash at end: */
      sprintf(cp, "%s%c%s", dirname, SLASH, "*.*");
   }

   if(debug) {
      qprintf(fp_out, "Able to allocate for %s.\n", cp);
      fflush(fp_out);
   }

   if((dp = new DIR) == NULL) {
      qprintf(stdout, "Unable to allocate memory.\n");
      return (NULL);
   }

   if(debug) {
      qprintf(fp_out, "About to call _findfirst().\n");
      fflush(fp_out);
   }


   /* find first file in specified directory */
   if((dp->handl = _findfirst( cp, &(dp->dev_dir) )) == -1L) {
      qprintf(stdout, "Sorry: there are no %s files.\n", cp);
      return (NULL);
   } 

   if(debug) {
      qprintf(fp_out, "Back from _findfirst().\n");
      fflush(fp_out);
   }


   dp->now_valid = 1;    /* we already have the first file... */

   return dp;
} /* end of opendir() */



// qxreaddir()

DIR_GUY *readdir(DIR *dfd) {
   static DIR_GUY dg;

   if(!dfd->now_valid) {
      /* the usual case, except right after opendir() */
      if( _findnext(dfd->handl, &(dfd->dev_dir) ) != 0 ) {
         /* end of list */
         return (NULL);
      }
   }
   sprintf(dg.d_name, "%s", dfd->dev_dir.name);
   dfd->now_valid = 0;

   // diagnostics re high ascii (extended ascii) chars:
   int iMax = -1;
   int iMin = 256;
   for(int i=0; i<strlen(dfd->dev_dir.name); i++) {
      int c = dfd->dev_dir.name[i];
      if(c < 0) c += 256;
      if(c < iMin) iMin = c;
      if(c > iMax) iMax = c;
   } // for(int i=0; i<strlen(dfd->dev_dir.name); i++)

   // qprintf(stdout, "Name \"%s\": chars from %d to %d.\n", dfd->dev_dir.name, iMin, iMax);


   return &dg;

} /* end of readdir() */




// qxclosedir()

void    closedir(DIR *dfd) {
   _findclose(dfd->handl);
// free(dfd);
   delete dfd;
} /* end of closedir() */

#endif // _WIN32



//
// recursive; appends to vecSrcFiles.
//
//
//
// 06-04-26: use vetSet to avoid duplicates.
// 06-08-26: handle blank dir_name.
//
// qxfillSrcFiles()

int fillSrcFiles(const char *dir_name, vetSet<std::string> &vtSrcFiles, int iDepth, bool bInclBotFoldrs) {
   SMARTA(pcFull, char, MAX_FULL_NAME_LEN, smaFull);

// char            extra[8];
// struct jdirinfo *p;
// struct stat     stbuf;     // out 01-07-18
   DIR_GUY         *dp;       // equivalent to K&R Dirent
   DIR             *dfd;

// fprintf(stdout, "This is fillSrcFiles() for dir: \"%s\", depth %d, bInclBot %d.\n", dir_name, iDepth, bInclBotFoldrs);    // qxtemp

   if(debug) {
      fprintf(fp_out, "This is fillSrcFiles() for dir: %s.\n", dir_name);
      fflush(fp_out);
   }

   int lenDir = (int)strlen(dir_name);     // if zero, we avoid adding ".\" to our files to make full name.

   std::string ssNameDir = dir_name;
   if(lenDir == 0) {
      ssNameDir = ".";
      ssNameDir += SLASH;
   } // if(lenDir == 0)


   vtSrcFiles.insert(ssNameDir);

   if(iDepth == 0)
      return (int)vtSrcFiles.size();

   std::vector<std::string> vecFolders;    // list of folders under us; we'll recurse after doing all data files

   bool bOneCall = false;
   // open the directory; read the files!

   if((dfd = opendir(ssNameDir.c_str())) == NULL) {
      fprintf(stdout,  "%s showed as directory, but couldn't open.\n", ssNameDir.c_str());
      return (int)vtSrcFiles.size();    // no change
   }

   while((dp = readdir(dfd)) != NULL) {
      if(strcmp(dp->d_name, ".") == 0)
         continue;

      if(strcmp(dp->d_name, "..") == 0)
         continue;


      if((lenDir == 0) || (is_slash(dir_name[lenDir-1]))) {
         sprintf(pcFull, "%s%s", dir_name, dp->d_name);        // lenDir 0 gets just dp->d_name
      } else {
         sprintf(pcFull, "%s%c%s", dir_name, SLASH, dp->d_name);
      }

      qprintf(stdout, "Looking at \"%s\" and \"%s\", making \"%s\".\n", dir_name, dp->d_name, pcFull);


#ifdef _WIN32
      struct _stat64  stbu64;     // for big file sizes (>2^31).
      if(_stat64(pcFull, &stbu64) == -1) {
#else
      struct stat64  stbu64;     // for big file sizes (>2^31).
      if(stat64(pcFull, &stbu64) == -1) {
#endif // !_WIN32
         fprintf(stdout,  "%s is NOT found.\n", pcFull);
         continue;   // qxl: verify action
      }

      if((stbu64.st_mode & S_IFMT) == S_IFDIR) {
         if(!is_slash(pcFull[strlen(pcFull) - 1]))
            sprintf(pcFull+strlen(pcFull), "%c", SLASH);  // append slash

//       qprintf(stdout, "pcFull after slash: \"%s\".\n", pcFull);  // qxtemp

         vecFolders.push_back(pcFull);
//       fprintf(stdout, "pushing folder file \"%s\".\n", pcFull);
      } else {
         // not a directory file: stuff immediately in output vector:
         vtSrcFiles.insert(pcFull);
//       fprintf(stdout, "pushing normal file \"%s\".\n", pcFull);
      }
   } // while((dp = readdir(dfd)) != NULL)

   closedir(dfd);

   if((iDepth == 1) && (!bInclBotFoldrs)) {
      // don't list folder names for which we are not going to list any data files.
   } else {
      // usual: recurse.
      int nDirs = (int)vecFolders.size();
      for(int i=0; i<nDirs; i++) {
         const std::string &ssDir = vecFolders[i];

         int jDepth = ((iDepth < 0) ? (iDepth) : (iDepth - 1));
         fillSrcFiles(ssDir.c_str(), vtSrcFiles, jDepth, bInclBotFoldrs);
      } // for(int i=0; i<nDirs; i++)
   } // !if((iDepth == 1) && (!bInclBotFoldrs))

// qprintf(stdout, "About to leave fillSrcFiles() with %d entries...\n", (int)vtSrcFiles.size());

   return (int)vtSrcFiles.size();
} // int fillSrcFiles()...




#ifdef DEAD_CODE  // there's a better version.

//
// new 07-24-23: only report files that match the spec(s).
//
//
//
//
//
// 07-25-23: empty vcSpecs allows anyone.
// 01-27-25: bool bJustThis -> int iDepth.
// 06-04-26: use vetSet to avoid duplicates.
//
// qxfillSpecdFiles()

int fillSpecdFiles(const char *dir_name, const std::vector<std::string> &vcSpecs, vetSet<std::string> &vtSrcFiles, int iDepth, bool bInclBotFoldrs) {
   int i = 0;

   std::vector<std::string> vecSrcLoc;
   vetSet<std::string>      vtSrcLoc;

   if(vcSpecs.size() == 0) {
      // we take that to mean that everyone is allowed.
//    int iRet = fillSrcFiles(dir_name, vecSrcFiles, bJustThis);
      int iRet = fillSrcFiles(dir_name, vtSrcFiles, iDepth, bInclBotFoldrs);

      return iRet;
   } // if(vcSpecs.size() == 0)

   // at least one spec passsed in:
   i = fillSrcFiles(dir_name, vtSrcLoc, iDepth, bInclBotFoldrs);
   if(i < 0)
      return i;

// fprintf(stdout, "Back from fillSrcFiles() with %d entries.\n", (int)vtSrcLoc.size());   // qxtemp!


   for(int ifil=0; ifil<(int)vtSrcLoc.size(); ifil++) {
      const unsigned char *pcCandidate = (const unsigned char *)vtSrcLoc[ifil].c_str();

      const char *pcFull = (const char *)pcCandidate;
      SMARTA(pcDir, char, (strlen(pcFull) + 32), smaDir);
      SMARTA(pcFil, char, (strlen(pcFull) + 32), smaFil);

      cut_file_name(pcFull, pcDir, pcFil);

//    fprintf(stdout, "We cut \"%s\" into \"%s\" and \"%s\".\n", pcFull, pcDir, pcFil);  // qxtemp!

      for(int ispec=0; ispec<(int)vcSpecs.size(); ispec++) {
         const unsigned char *pcSpec = (const unsigned char *)vcSpecs[ispec].c_str();
//       fprintf(stdout, "Calling match() for \"%s\" and \"%s\".\n", pcSpec, pcFil);   // qxtemp!
         if(match(pcSpec, (const unsigned char *)pcFil, lwc)) {
            // ajAnch.addOne((const char *)pcCandidate, iFormat);
            vtSrcFiles.insert(pcFull);
            break;
         } // if(match(pcSpec, pcCandidate, lwc))
      } // for(int ispec=0; ispec<(int)vcFiles.size(); ispec++)
   } // for(int ifil=0; ifil<(int)vtSrcFiles.size(); ifil++)


   return (int)vtSrcFiles.size();
} // int fillSpecdFiles()...


#endif // DEAD_CODE  // there's a better version.



//
// new 07-24-23: only report files that match the spec(s).
//
// Input:
//    dir_name:  directory name to search
//    vcSpecs:   if empty, anyone; otherwise only files that match one of the specs (can include wilds).
//    vcExclude: overrides all else: exclude any files meeting this (can include wilds).
//    iDepth:    -1: go forever; 0: directory name but no contents; 1: just this folder.
//    bInclBotFoldrs: if true, include folder names we won't examine for data files (iDepth 1).
//
// Output:
//    vtSrcFiles: appended to as specified.
//
//
//
//
// 07-25-23: empty vcSpecs allows anyone.
// 07-25-23: add vcExclude.
// 06-04-26: use vetSet to avoid duplicates.
//
// qxfillSpecdFiles()

int fillSpecdFiles(const char *dir_name, const std::vector<std::string> &vcSpecs, const std::vector<std::string> &vcExclude, vetSet<std::string> &vtSrcFiles, int iDepth, bool bInclBotFoldrs) {
   int i = 0;

   std::vector<std::string> vecSrcLoc;
   vetSet<std::string>      vtSrcLoc;

   if((vcSpecs.size() == 0) && (vcExclude.size() == 0)) {
      // we take that to mean that everyone is allowed.
      int iRet = fillSrcFiles(dir_name, vtSrcFiles, iDepth, bInclBotFoldrs);

      return iRet;
   }

   // at least one spec and/or exclude passsed in:
   i = fillSrcFiles(dir_name, vtSrcLoc, iDepth, bInclBotFoldrs);
   if(i < 0)
      return i;

// qprintf(stdout, "ready to check spec(s).\n");


   for(int ifil=0; ifil<(int)vtSrcLoc.size(); ifil++) {
      const unsigned char *pcCandidate = (const unsigned char *)vtSrcLoc[ifil].c_str();

//    fprintf(stdout, "Considering file \"%s\".\n", pcCandidate);  // qxtemp!

      const char *pcFull = (const char *)pcCandidate;
      SMARTA(pcDir, char, (strlen(pcFull) + 32), smaDir);
      SMARTA(pcFil, char, (strlen(pcFull) + 32), smaFil);

      cut_file_name(pcFull, pcDir, pcFil);

      if((strlen(pcFil) > 0) && (is_slash(pcFil[strlen(pcFil)-1])))
         pcFil[strlen(pcFil)-1] = '\0';

      qprintf(fp_dbg, "Considering file \"%s\", cut into \"%s\" and \"%s\".\n", pcCandidate, pcDir, pcFil);  // qxtemp!
//    qprintf(stdout, "Considering file \"%s\", cut into \"%s\" and \"%s\".\n", pcCandidate, pcDir, pcFil);  // qxtemp!

      bool bSkip = false;

      // if this file is on the excluded list, that overrides everything:
      for(int iexcl=0; iexcl<(int)vcExclude.size(); iexcl++) {
         const unsigned char *pcExcl = (const unsigned char *)vcExclude[iexcl].c_str();
         if(match(pcExcl, (const unsigned char *)pcFil, lwc)) {
            bSkip = true;
//          fprintf(stdout, "Match between \"%s\" and \"%s\" means we skip.\n", pcExcl, pcFil);  // qxtemp!
            break;
         } // if(match(pcExcl, pcCandidate, lwc))
      } // for(int iexcl=0; iexcl<(int)vcExclude.size(); iexcl++)

      if(bSkip)
         continue;


      if(vcSpecs.size() == 0) {
         // assume the file is good to include.  bSkip is already false.
      } else {
         bSkip = true;   // unless we like it below.
         for(int ispec=0; ispec<(int)vcSpecs.size(); ispec++) {
            const unsigned char *pcSpec = (const unsigned char *)vcSpecs[ispec].c_str();
            if(match(pcSpec, (const unsigned char *)pcFil, lwc)) {
               // ajAnch.addOne((const char *)pcCandidate, iFormat);
               bSkip = false;
//             fprintf(stdout, "Match between \"%s\" and \"%s\" means we keep.\n", pcSpec, pcFil);  // qxtemp!
               break;
            } // if(match(pcSpec, pcCandidate, lwc))
         } // for(int ispec=0; ispec<(int)vcSpecs.size(); ispec++)
      } // !if(vcSpecs.size() == 0)

      if(bSkip)
         continue;

//    fprintf(stdout, "We like file \"%s\".\n", pcFull);  // qxtemp!

      // we like it:
      vtSrcFiles.insert(pcFull);
   } // for(int ifil=0; ifil<(int)tcSrcFiles.size(); ifil++)

   return (int)vtSrcFiles.size();
} // int fillSpecdFiles()...




// qxhas_wilds()

int has_wilds(const unsigned char *name) {
   int c;
   const unsigned char *cp, *cp2;

   for(cp=name, cp2=name+(int)strlen((const char *)name); cp != cp2; cp++) {
      switch(c = *cp) {
         case '*':
         case '@':          // Linux substitute for '*' to avoid pre-processing
         case '?':
         case '[':
         case '%':          // Linux substitute for '?' to avoid pre-processing
            return 1;
            break;
         default:
            // continue looking...
            break;
      } // switch(c = *cp)
   } // for(cp=name, cp2=name+(int)strlen((const char *)name); cp != cp2; cp++)

   return 0;
} // end of has_wilds()...







