/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const MAX_ATTEMPTS = 5;
const fileFinder = module.exports;

/**
 * Gets contents of a directory
 *
 * @param {String} directory
 * @param {Array} contents of a directory
 */
function getDirectoryEntries(directory) {
  try {
    return fs.readdirSync(directory);
  } catch (ex) {
    return [];
  }
}

/**
 * Filters files with name matching the file param
 *
 * @param {String} directory path to check for file
 * @param {Array} files list of entries in a directory
 * @param {String} file file to check
 *
 * @return {*} path to file file or false
 */
function filterFiles(directory, files, file) {
  const hit = files.filter((entry) => entry === file)[0];
  return hit ? path.resolve(directory, hit) : false;
}

/**
 * Checks each direct sibling folder for file
 *
 * @param {Object} params
 * @param {String} params.file file to check
 * @param {String} params.directory path to check for file
 * @param {Array} params.foundFiles array to hold found files
 * @param {Array} params.entries list of directory contents
 */
function checkNestedFolders({ file, directory, entries, foundFiles }) {
  entries.reduce((foundFiles, entry) => {
    const resolvedEntry = path.resolve(directory, entry);
    try {
      if (!fs.statSync(resolvedEntry).isFile()) {
        const path = filterFiles(
          resolvedEntry,
          getDirectoryEntries(resolvedEntry),
          file
        );
        if (path) {
          foundFiles.push(path);
        }
      }
    } catch (err) {
      // swallow this error, we don't care
    }
    return foundFiles;
  }, foundFiles);
}

/**
 * Tries to find a file in entryPoint, 1 folder below or up to 5 directories
 * above initial path
 *
 * @param {Object} params
 * @param {String} params.directory path to check for file
 * @param {String} params.file file to check
 * @param {Int} [params.maxAttempts=5] max attempts to check above params.directory
 * @param {Int} params.attempts current attempt to find file in path
 * @param {Boolean} params.checkNested flag to check in nested directories
 *
 * @return {String} path to file
 */
function findFile({
  directory,
  file,
  maxAttempts = MAX_ATTEMPTS,
  attempts = 0,
  checkNested = true
}) {
  if (attempts >= maxAttempts) {
    return;
  }

  attempts++;
  directory = path.resolve(directory);

  const entries = getDirectoryEntries(directory);
  const location = filterFiles(directory, entries, file);
  if (location) {
    return location;
  }

  // we only want to check files for each directory in the intial call to this function
  if (checkNested) {
    const foundFiles = [];
    checkNestedFolders({ directory, entries, file, foundFiles });
    // we found a file in the child folders return path to it
    if (foundFiles.length > 0) {
      return foundFiles[0];
    }
  }

  // we only want to look at dirs in the intial directory
  // assign parent directory to directory
  directory = path.dirname(directory);
  return findFile({
    directory,
    file,
    maxAttempts,
    attempts,
    checkNested: false
  });
}

/**
 * Tries to find a file in entryPoint, 1 folder below or up to 5 directories
 * above initial path
 *
 * @param {String} entryPoint path to file
 * @param {String} file file to find
 * @param {Int} maxAttempts max number of attempts
 */
fileFinder.findFile = function(entryPoint, file, maxAttempts) {
  return findFile({ directory: entryPoint, file, maxAttempts });
};

/**
 * Tries to read a file 2 directories up from current running path
 *
 * @param {String} path to file
 * @return {*} file buffer or err object
 */
fileFinder.readFilePath = function(filePath) {
  // check for caFile bundled with the tarball
  try {
    const resFilePath = path.resolve(__dirname, '..', '..', filePath);
    return fs.readFileSync(resFilePath);
  } catch (err) {
    return err;
  }
};
