/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmFindCommon.h"

#include <algorithm>
#include <array>
#include <utility>

#include <cmext/algorithm>

#include "cmExecutionStatus.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmake.h"

cmFindCommon::PathGroup cmFindCommon::PathGroup::All("ALL");
cmFindCommon::PathLabel cmFindCommon::PathLabel::PackageRoot(
  "PackageName_ROOT");
cmFindCommon::PathLabel cmFindCommon::PathLabel::CMake("CMAKE");
cmFindCommon::PathLabel cmFindCommon::PathLabel::CMakeEnvironment(
  "CMAKE_ENVIRONMENT");
cmFindCommon::PathLabel cmFindCommon::PathLabel::Hints("HINTS");
cmFindCommon::PathLabel cmFindCommon::PathLabel::SystemEnvironment(
  "SYSTM_ENVIRONMENT");
cmFindCommon::PathLabel cmFindCommon::PathLabel::CMakeSystem("CMAKE_SYSTEM");
cmFindCommon::PathLabel cmFindCommon::PathLabel::Guess("GUESS");

cmFindCommon::cmFindCommon(cmExecutionStatus& status)
  : Makefile(&status.GetMakefile())
  , Status(status)
{
  FindRootPathMode = RootPathModeBoth;
  NoDefaultPath = false;
  NoPackageRootPath = false;
  NoCMakePath = false;
  NoCMakeEnvironmentPath = false;
  NoSystemEnvironmentPath = false;
  NoCMakeSystemPath = false;

// OS X Bundle and Framework search policy.  The default is to
// search frameworks first on apple.
#if defined(__APPLE__)
  this->SearchFrameworkFirst = true;
  this->SearchAppBundleFirst = true;
#else
  SearchFrameworkFirst = false;
  SearchAppBundleFirst = false;
#endif
  SearchFrameworkOnly = false;
  SearchFrameworkLast = false;
  SearchAppBundleOnly = false;
  SearchAppBundleLast = false;

  InitializeSearchPathGroups();

  DebugMode = false;
}

void cmFindCommon::SetError(std::string const& e)
{
  Status.SetError(e);
}

void cmFindCommon::DebugMessage(std::string const& msg) const
{
  if (Makefile) {
    Makefile->IssueMessage(MessageType::LOG, msg);
  }
}

bool cmFindCommon::ComputeIfDebugModeWanted()
{
  return Makefile->IsOn("CMAKE_FIND_DEBUG_MODE") ||
    Makefile->GetCMakeInstance()->GetDebugFindOutput();
}

void cmFindCommon::InitializeSearchPathGroups()
{
  std::vector<PathLabel>* labels;

  // Define the various different groups of path types

  // All search paths
  labels = &PathGroupLabelMap[PathGroup::All];
  labels->push_back(PathLabel::PackageRoot);
  labels->push_back(PathLabel::CMake);
  labels->push_back(PathLabel::CMakeEnvironment);
  labels->push_back(PathLabel::Hints);
  labels->push_back(PathLabel::SystemEnvironment);
  labels->push_back(PathLabel::CMakeSystem);
  labels->push_back(PathLabel::Guess);

  // Define the search group order
  PathGroupOrder.push_back(PathGroup::All);

  // Create the individual labeled search paths
  LabeledPaths.insert(
    std::make_pair(PathLabel::PackageRoot, cmSearchPath(this)));
  LabeledPaths.insert(std::make_pair(PathLabel::CMake, cmSearchPath(this)));
  LabeledPaths.insert(
    std::make_pair(PathLabel::CMakeEnvironment, cmSearchPath(this)));
  LabeledPaths.insert(std::make_pair(PathLabel::Hints, cmSearchPath(this)));
  LabeledPaths.insert(
    std::make_pair(PathLabel::SystemEnvironment, cmSearchPath(this)));
  LabeledPaths.insert(
    std::make_pair(PathLabel::CMakeSystem, cmSearchPath(this)));
  LabeledPaths.insert(std::make_pair(PathLabel::Guess, cmSearchPath(this)));
}

void cmFindCommon::SelectDefaultRootPathMode()
{
  // Check the policy variable for this find command type.
  std::string findRootPathVar =
    cmStrCat("CMAKE_FIND_ROOT_PATH_MODE_", CMakePathName);
  std::string rootPathMode = Makefile->GetSafeDefinition(findRootPathVar);
  if (rootPathMode == "NEVER") {
    FindRootPathMode = RootPathModeNever;
  } else if (rootPathMode == "ONLY") {
    FindRootPathMode = RootPathModeOnly;
  } else if (rootPathMode == "BOTH") {
    FindRootPathMode = RootPathModeBoth;
  }
}

void cmFindCommon::SelectDefaultMacMode()
{
  std::string ff = Makefile->GetSafeDefinition("CMAKE_FIND_FRAMEWORK");
  if (ff == "NEVER") {
    SearchFrameworkLast = false;
    SearchFrameworkFirst = false;
    SearchFrameworkOnly = false;
  } else if (ff == "ONLY") {
    SearchFrameworkLast = false;
    SearchFrameworkFirst = false;
    SearchFrameworkOnly = true;
  } else if (ff == "FIRST") {
    SearchFrameworkLast = false;
    SearchFrameworkFirst = true;
    SearchFrameworkOnly = false;
  } else if (ff == "LAST") {
    SearchFrameworkLast = true;
    SearchFrameworkFirst = false;
    SearchFrameworkOnly = false;
  }

  std::string fab = Makefile->GetSafeDefinition("CMAKE_FIND_APPBUNDLE");
  if (fab == "NEVER") {
    SearchAppBundleLast = false;
    SearchAppBundleFirst = false;
    SearchAppBundleOnly = false;
  } else if (fab == "ONLY") {
    SearchAppBundleLast = false;
    SearchAppBundleFirst = false;
    SearchAppBundleOnly = true;
  } else if (fab == "FIRST") {
    SearchAppBundleLast = false;
    SearchAppBundleFirst = true;
    SearchAppBundleOnly = false;
  } else if (fab == "LAST") {
    SearchAppBundleLast = true;
    SearchAppBundleFirst = false;
    SearchAppBundleOnly = false;
  }
}

void cmFindCommon::SelectDefaultSearchModes()
{
  const std::array<std::pair<bool&, std::string>, 5> search_paths = {
    { { NoPackageRootPath, "CMAKE_FIND_USE_PACKAGE_ROOT_PATH" },
      { NoCMakePath, "CMAKE_FIND_USE_CMAKE_PATH" },
      { NoCMakeEnvironmentPath, "CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH" },
      { NoSystemEnvironmentPath, "CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH" },
      { NoCMakeSystemPath, "CMAKE_FIND_USE_CMAKE_SYSTEM_PATH" } }
  };

  for (auto& path : search_paths) {
    cmProp def = Makefile->GetDefinition(path.second);
    if (def) {
      path.first = !cmIsOn(*def);
    }
  }
}

void cmFindCommon::RerootPaths(std::vector<std::string>& paths)
{
#if 0
  for(std::string const& p : paths)
    {
    fprintf(stderr, "[%s]\n", p.c_str());
    }
#endif
  // Short-circuit if there is nothing to do.
  if (FindRootPathMode == RootPathModeNever) {
    return;
  }

  cmProp sysroot = Makefile->GetDefinition("CMAKE_SYSROOT");
  cmProp sysrootCompile = Makefile->GetDefinition("CMAKE_SYSROOT_COMPILE");
  cmProp sysrootLink = Makefile->GetDefinition("CMAKE_SYSROOT_LINK");
  cmProp rootPath = Makefile->GetDefinition("CMAKE_FIND_ROOT_PATH");
  const bool noSysroot = !cmNonempty(sysroot);
  const bool noCompileSysroot = !cmNonempty(sysrootCompile);
  const bool noLinkSysroot = !cmNonempty(sysrootLink);
  const bool noRootPath = !cmNonempty(rootPath);
  if (noSysroot && noCompileSysroot && noLinkSysroot && noRootPath) {
    return;
  }

  // Construct the list of path roots with no trailing slashes.
  std::vector<std::string> roots;
  if (rootPath) {
    cmExpandList(*rootPath, roots);
  }
  if (sysrootCompile) {
    roots.emplace_back(*sysrootCompile);
  }
  if (sysrootLink) {
    roots.emplace_back(*sysrootLink);
  }
  if (sysroot) {
    roots.emplace_back(*sysroot);
  }
  for (std::string& r : roots) {
    cmSystemTools::ConvertToUnixSlashes(r);
  }

  cmProp stagePrefix = Makefile->GetDefinition("CMAKE_STAGING_PREFIX");

  // Copy the original set of unrooted paths.
  std::vector<std::string> unrootedPaths = paths;
  paths.clear();

  for (std::string const& r : roots) {
    for (std::string const& up : unrootedPaths) {
      // Place the unrooted path under the current root if it is not
      // already inside.  Skip the unrooted path if it is relative to
      // a user home directory or is empty.
      std::string rootedDir;
      if (cmSystemTools::IsSubDirectory(up, r) ||
          (stagePrefix && cmSystemTools::IsSubDirectory(up, *stagePrefix))) {
        rootedDir = up;
      } else if (!up.empty() && up[0] != '~') {
        // Start with the new root.
        rootedDir = cmStrCat(r, '/');

        // Append the original path with its old root removed.
        rootedDir += cmSystemTools::SplitPathRootComponent(up);
      }

      // Store the new path.
      paths.push_back(rootedDir);
    }
  }

  // If searching both rooted and unrooted paths add the original
  // paths again.
  if (FindRootPathMode == RootPathModeBoth) {
    cm::append(paths, unrootedPaths);
  }
}

void cmFindCommon::GetIgnoredPaths(std::vector<std::string>& ignore)
{
  // null-terminated list of paths.
  static const char* paths[] = { "CMAKE_SYSTEM_IGNORE_PATH",
                                 "CMAKE_IGNORE_PATH", nullptr };

  // Construct the list of path roots with no trailing slashes.
  for (const char** pathName = paths; *pathName; ++pathName) {
    // Get the list of paths to ignore from the variable.
    Makefile->GetDefExpandList(*pathName, ignore);
  }

  for (std::string& i : ignore) {
    cmSystemTools::ConvertToUnixSlashes(i);
  }
}

void cmFindCommon::GetIgnoredPaths(std::set<std::string>& ignore)
{
  std::vector<std::string> ignoreVec;
  GetIgnoredPaths(ignoreVec);
  ignore.insert(ignoreVec.begin(), ignoreVec.end());
}

bool cmFindCommon::CheckCommonArgument(std::string const& arg)
{
  if (arg == "NO_DEFAULT_PATH") {
    NoDefaultPath = true;
  } else if (arg == "NO_PACKAGE_ROOT_PATH") {
    NoPackageRootPath = true;
  } else if (arg == "NO_CMAKE_PATH") {
    NoCMakePath = true;
  } else if (arg == "NO_CMAKE_ENVIRONMENT_PATH") {
    NoCMakeEnvironmentPath = true;
  } else if (arg == "NO_SYSTEM_ENVIRONMENT_PATH") {
    NoSystemEnvironmentPath = true;
  } else if (arg == "NO_CMAKE_SYSTEM_PATH") {
    NoCMakeSystemPath = true;
  } else if (arg == "NO_CMAKE_FIND_ROOT_PATH") {
    FindRootPathMode = RootPathModeNever;
  } else if (arg == "ONLY_CMAKE_FIND_ROOT_PATH") {
    FindRootPathMode = RootPathModeOnly;
  } else if (arg == "CMAKE_FIND_ROOT_PATH_BOTH") {
    FindRootPathMode = RootPathModeBoth;
  } else {
    // The argument is not one of the above.
    return false;
  }

  // The argument is one of the above.
  return true;
}

void cmFindCommon::AddPathSuffix(std::string const& arg)
{
  std::string suffix = arg;

  // Strip leading and trailing slashes.
  if (suffix.empty()) {
    return;
  }
  if (suffix.front() == '/') {
    suffix = suffix.substr(1);
  }
  if (suffix.empty()) {
    return;
  }
  if (suffix.back() == '/') {
    suffix = suffix.substr(0, suffix.size() - 1);
  }
  if (suffix.empty()) {
    return;
  }

  // Store the suffix.
  SearchPathSuffixes.push_back(std::move(suffix));
}

void AddTrailingSlash(std::string& s)
{
  if (!s.empty() && s.back() != '/') {
    s += '/';
  }
}
void cmFindCommon::ComputeFinalPaths()
{
  // Filter out ignored paths from the prefix list
  std::set<std::string> ignored;
  GetIgnoredPaths(ignored);

  // Combine the separate path types, filtering out ignores
  SearchPaths.clear();
  std::vector<PathLabel>& allLabels = PathGroupLabelMap[PathGroup::All];
  for (PathLabel const& l : allLabels) {
    LabeledPaths[l].ExtractWithout(ignored, SearchPaths);
  }

  // Expand list of paths inside all search roots.
  RerootPaths(SearchPaths);

  // Add a trailing slash to all paths to aid the search process.
  std::for_each(SearchPaths.begin(), SearchPaths.end(), &AddTrailingSlash);
}
