// Compiler for PHP (aka KPHP)
// Copyright (c) 2023 LLC «V Kontakte»
// Distributed under the GPL v3 License, see LICENSE.notice.txt

#include "compiler/code-gen/files/cmake-lists-txt.h"

#include <filesystem>
#include <fstream>

#include "compiler/code-gen/common.h"
#include "compiler/compiler-core.h"
#include "common/wrappers/fmt_format.h"

void CmakeListsTxt::compile_include_cmake() const noexcept {
  // 1) creating of file outside of CompilerSettings::dest_cpp_dir directory is unable with CodeGenerator,
  // therefore this simple proxy file is created via std::ofstream
  // 2) don't change mtime of this file since it trigger pointless minor reindexing IDE's project,

  std::filesystem::path file_path{G->settings().kphp_src_path.get()};
  file_path /= "objs/custom_php_project.cmake";
  if (!std::filesystem::exists(file_path)) {
     std::ofstream file{file_path};
     file << "add_subdirectory(" << G->settings().dest_cpp_dir.get() << ")";
  }
}

void CmakeListsTxt::compile_cmake_lists_txt(CodeGenerator &W) const noexcept {
  W << OpenFile{"CMakeLists.txt", {}, false, false};
  const std::string target_name{"autogen_" + G->settings().mode.get()};

  W <<  fmt_format(R"cmake(#[[
this CMakeLists.txt is autogenerated. It serves two purposes:
1) mostly to make IDE aware about *.cpp sources having been transpiled by kphp
2) but it also possible to use it for building *.cpp sources into final binary
]]
cmake_minimum_required(VERSION 3.16)
project({0} LANGUAGES CXX)

file(GLOB_RECURSE SRC_FILES ${{CMAKE_CURRENT_SOURCE_DIR}}/*.cpp)

add_executable({0} EXCLUDE_FROM_ALL ${{SRC_FILES}})
target_include_directories({0} PRIVATE . ${{AUTO_DIR}}/runtime/)
target_link_libraries({0} PRIVATE ${{RUNTIME_LIBS}} ${{RUNTIME_LINK_TEST_LIBS}}))cmake", target_name);

  W << CloseFile{};
}

void CmakeListsTxt::compile(CodeGenerator &W) const noexcept {
  compile_include_cmake();
  compile_cmake_lists_txt(W);
}
