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

#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <sstream>

#include <cmext/string_view>

#include "cmCTest.h"
#include "cmCTestGenericHandler.h"
#include "cmExecutionStatus.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmProperty.h"
#include "cmStringAlgorithms.h"
#include "cmSystemTools.h"
#include "cmWorkingDirectory.h"

namespace {
// class to save and restore the error state for ctest_* commands
// if a ctest_* command has a CAPTURE_CMAKE_ERROR then put the error
// state into there and restore the system wide error to what
// it was before the command ran
class SaveRestoreErrorState
{
public:
  SaveRestoreErrorState()
  {
    InitialErrorState = cmSystemTools::GetErrorOccuredFlag();
    cmSystemTools::ResetErrorOccuredFlag(); // rest the error state
    CaptureCMakeErrorValue = false;
  }
  // if the function has a CAPTURE_CMAKE_ERROR then we should restore
  // the error state to what it was before the function was run
  // if not then let the error state be what it is
  void CaptureCMakeError() { CaptureCMakeErrorValue = true; }
  ~SaveRestoreErrorState()
  {
    // if we are not saving the return value then make sure
    // if it was in error it goes back to being in error
    // otherwise leave it be what it is
    if (!CaptureCMakeErrorValue) {
      if (InitialErrorState) {
        cmSystemTools::SetErrorOccured();
      }
      return;
    }
    // if we have saved the error in a return variable
    // then put things back exactly like they were
    bool currentState = cmSystemTools::GetErrorOccuredFlag();
    // if the state changed during this command we need
    // to handle it, if not then nothing needs to be done
    if (currentState != InitialErrorState) {
      // restore the initial error state
      if (InitialErrorState) {
        cmSystemTools::SetErrorOccured();
      } else {
        cmSystemTools::ResetErrorOccuredFlag();
      }
    }
  }
  SaveRestoreErrorState(const SaveRestoreErrorState&) = delete;
  SaveRestoreErrorState& operator=(const SaveRestoreErrorState&) = delete;

private:
  bool InitialErrorState;
  bool CaptureCMakeErrorValue;
};
}

bool cmCTestHandlerCommand::InitialPass(std::vector<std::string> const& args,
                                        cmExecutionStatus& status)
{
  // save error state and restore it if needed
  SaveRestoreErrorState errorState;
  // Allocate space for argument values.
  BindArguments();

  // Process input arguments.
  std::vector<std::string> unparsedArguments;
  std::vector<std::string> keywordsMissingValue;
  std::vector<std::string> parsedKeywords;
  Parse(args, &unparsedArguments, &keywordsMissingValue, &parsedKeywords);
  CheckArguments(keywordsMissingValue);

  std::sort(parsedKeywords.begin(), parsedKeywords.end());
  auto it = std::adjacent_find(parsedKeywords.begin(), parsedKeywords.end());
  if (it != parsedKeywords.end()) {
    Makefile->IssueMessage(
      MessageType::FATAL_ERROR,
      cmStrCat("Called with more than one value for ", *it));
  }

  bool const foundBadArgument = !unparsedArguments.empty();
  if (foundBadArgument) {
    SetError(cmStrCat("called with unknown argument \"",
                      unparsedArguments.front(), "\"."));
  }
  bool const captureCMakeError = !CaptureCMakeError.empty();
  // now that arguments are parsed check to see if there is a
  // CAPTURE_CMAKE_ERROR specified let the errorState object know.
  if (captureCMakeError) {
    errorState.CaptureCMakeError();
  }
  // if we found a bad argument then exit before running command
  if (foundBadArgument) {
    // store the cmake error
    if (captureCMakeError) {
      Makefile->AddDefinition(CaptureCMakeError, "-1");
      std::string const err = GetName() + " " + status.GetError();
      if (!cmSystemTools::FindLastString(err.c_str(), "unknown error.")) {
        cmCTestLog(CTest, ERROR_MESSAGE, err << " error from command\n");
      }
      // return success because failure is recorded in CAPTURE_CMAKE_ERROR
      return true;
    }
    // return failure because of bad argument
    return false;
  }

  // Set the config type of this ctest to the current value of the
  // CTEST_CONFIGURATION_TYPE script variable if it is defined.
  // The current script value trumps the -C argument on the command
  // line.
  cmProp ctestConfigType = Makefile->GetDefinition("CTEST_CONFIGURATION_TYPE");
  if (ctestConfigType) {
    CTest->SetConfigType(*ctestConfigType);
  }

  if (!Build.empty()) {
    CTest->SetCTestConfiguration(
      "BuildDirectory", cmSystemTools::CollapseFullPath(Build), Quiet);
  } else {
    std::string const& bdir =
      Makefile->GetSafeDefinition("CTEST_BINARY_DIRECTORY");
    if (!bdir.empty()) {
      CTest->SetCTestConfiguration(
        "BuildDirectory", cmSystemTools::CollapseFullPath(bdir), Quiet);
    } else {
      cmCTestLog(CTest, ERROR_MESSAGE,
                 "CTEST_BINARY_DIRECTORY not set" << std::endl;);
    }
  }
  if (!Source.empty()) {
    cmCTestLog(CTest, DEBUG,
               "Set source directory to: " << Source << std::endl);
    CTest->SetCTestConfiguration(
      "SourceDirectory", cmSystemTools::CollapseFullPath(Source), Quiet);
  } else {
    CTest->SetCTestConfiguration(
      "SourceDirectory",
      cmSystemTools::CollapseFullPath(
        Makefile->GetSafeDefinition("CTEST_SOURCE_DIRECTORY")),
      Quiet);
  }

  if (cmProp changeId = Makefile->GetDefinition("CTEST_CHANGE_ID")) {
    CTest->SetCTestConfiguration("ChangeId", *changeId, Quiet);
  }

  cmCTestLog(CTest, DEBUG, "Initialize handler" << std::endl;);
  cmCTestGenericHandler* handler = InitializeHandler();
  if (!handler) {
    cmCTestLog(CTest, ERROR_MESSAGE,
               "Cannot instantiate test handler " << GetName() << std::endl);
    if (captureCMakeError) {
      Makefile->AddDefinition(CaptureCMakeError, "-1");
      std::string const& err = status.GetError();
      if (!cmSystemTools::FindLastString(err.c_str(), "unknown error.")) {
        cmCTestLog(CTest, ERROR_MESSAGE, err << " error from command\n");
      }
      return true;
    }
    return false;
  }

  handler->SetAppendXML(Append);

  handler->PopulateCustomVectors(Makefile);
  if (!SubmitIndex.empty()) {
    handler->SetSubmitIndex(atoi(SubmitIndex.c_str()));
  }
  cmWorkingDirectory workdir(CTest->GetCTestConfiguration("BuildDirectory"));
  if (workdir.Failed()) {
    SetError("failed to change directory to " +
             CTest->GetCTestConfiguration("BuildDirectory") + " : " +
             std::strerror(workdir.GetLastResult()));
    if (captureCMakeError) {
      Makefile->AddDefinition(CaptureCMakeError, "-1");
      cmCTestLog(CTest, ERROR_MESSAGE,
                 GetName() << " " << status.GetError() << "\n");
      // return success because failure is recorded in CAPTURE_CMAKE_ERROR
      return true;
    }
    return false;
  }

  int res = handler->ProcessHandler();
  if (!ReturnValue.empty()) {
    Makefile->AddDefinition(ReturnValue, std::to_string(res));
  }
  ProcessAdditionalValues(handler);
  // log the error message if there was an error
  if (captureCMakeError) {
    const char* returnString = "0";
    if (cmSystemTools::GetErrorOccuredFlag()) {
      returnString = "-1";
      std::string const& err = status.GetError();
      // print out the error if it is not "unknown error" which means
      // there was no message
      if (!cmSystemTools::FindLastString(err.c_str(), "unknown error.")) {
        cmCTestLog(CTest, ERROR_MESSAGE, err);
      }
    }
    // store the captured cmake error state 0 or -1
    Makefile->AddDefinition(CaptureCMakeError, returnString);
  }
  return true;
}

void cmCTestHandlerCommand::ProcessAdditionalValues(cmCTestGenericHandler*)
{
}

void cmCTestHandlerCommand::BindArguments()
{
  Bind("APPEND"_s, Append);
  Bind("QUIET"_s, Quiet);
  Bind("RETURN_VALUE"_s, ReturnValue);
  Bind("CAPTURE_CMAKE_ERROR"_s, CaptureCMakeError);
  Bind("SOURCE"_s, Source);
  Bind("BUILD"_s, Build);
  Bind("SUBMIT_INDEX"_s, SubmitIndex);
}

void cmCTestHandlerCommand::CheckArguments(std::vector<std::string> const&)
{
}
