# Copyright 2022 The TensorStore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# NOTE: This is still very much a work in progress; It is not yet expected to
# build.

cmake_minimum_required(VERSION 3.24)
project(tensorstore LANGUAGES C CXX)

# Enable CMP0077 (option honors variables) for subprojects.
set(CMAKE_POLICY_DEFAULT_CMP0077 NEW)

# Enable CMP0126 for subprojects to prevent `set(<var> CACHE)`
# overriding a prior `set(<var>)` call.
set(CMAKE_POLICY_DEFAULT_CMP0126 NEW)

# Do not add the current directory to build commands by default.
# This is defensive, as the setting may be inherited from parents,
# and it has been known to cause errors in Abseil CMake builds.
set(CMAKE_INCLUDE_CURRENT_DIR OFF)

# Set all outputs to a single /bin directory.
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

set(CMAKE_CXX_STANDARD 20)

if(PROJECT_IS_TOP_LEVEL)
  include(CTest)
  enable_testing()

  # Use lld if it is available.
  if (NOT MSVC AND CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
      find_program(LLD_EXECUTABLE lld)
      if (LLD_EXECUTABLE)
          set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld")
          set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fuse-ld=lld")
          set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -fuse-ld=lld")
      endif()
  endif()

else()
  # Exclude targets from ALL when built as a sub-project.
  set_directory_properties(PROPERTIES EXCLUDE_FROM_ALL TRUE)
endif()

list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}/tools/cmake)

##
## Using tensorstore targets
##
## all public tensorstore targets are
## exported with the tensorstore:: prefix
##
## DO NOT rely on the internal targets outside of the prefix

## Abseil requires PIC code; we generally use the same.
set(CMAKE_POSITION_INDEPENDENT_CODE TRUE)

find_package(Threads REQUIRED)

if(MSVC AND (PROJECT_IS_TOP_LEVEL OR
             CMAKE_CXX_COMPILER_LAUNCHER MATCHES "sccache"))
  option(TENSORSTORE_MSVC_USE_Z7
         "Use /Z7 and disable incremental linking on MSVC" ON)
endif()

if(TENSORSTORE_MSVC_USE_Z7)
  # /Zi spawns a separate mspdbsrv.exe process to build pdb files, which CMake
  # enables by default and is incompatible with sccache.
  # https://github.com/mozilla/sccache#usage
  #
  # So we convert /Zi to /Z7.
  #
  # With /Z7, MSVC's default /INCREMENTAL linker flag generates huge .ilk
  # files (~15-20 GiB across all test binaries). So when we convert /Zi to /Z7
  # we also disable incremental linking.
  #
  # Note that this unavoidably affects the entire build, not just this project.
  foreach(config IN ITEMS DEBUG RELEASE RELWITHDEBINFO)
    string(REPLACE "/Zi" "/Z7"
           CMAKE_CXX_FLAGS_${config} "${CMAKE_CXX_FLAGS_${config}}")
    string(REPLACE "/Zi" "/Z7"
           CMAKE_C_FLAGS_${config} "${CMAKE_C_FLAGS_${config}}")
    foreach(kind IN ITEMS EXE SHARED MODULE)
      string(REPLACE "/INCREMENTAL:NO" "/INCREMENTAL"
             CMAKE_${kind}_LINKER_FLAGS_${config}
             "${CMAKE_${kind}_LINKER_FLAGS_${config}}")
      string(REPLACE "/INCREMENTAL" "/INCREMENTAL:NO"
             CMAKE_${kind}_LINKER_FLAGS_${config}
             "${CMAKE_${kind}_LINKER_FLAGS_${config}}")
    endforeach()
  endforeach()
endif()

# See bazelrc for this
if(MINGW)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wa,-mbig-obj")
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wa,-mbig-obj")
endif()

if(APPLE)
    # Suppress warnings about duplicate libraries being ignored, which are common
    # due to the transitive dependency model used by bazel_to_cmake.  The flag is
    # only supported by the Xcode 15+ linker, so check for it first.
    include(CheckLinkerFlag)
    check_linker_flag(CXX "LINKER:-no_warn_duplicate_libraries"
                      TENSORSTORE_LINKER_NO_WARN_DUPLICATE_LIBRARIES)
    if(TENSORSTORE_LINKER_NO_WARN_DUPLICATE_LIBRARIES)
        add_link_options("LINKER:-no_warn_duplicate_libraries")
    endif()
endif()

include(bazel_to_cmake)

bazel_to_cmake(
  --cmake-project-name tensorstore
  --bazel-repo-name tensorstore
  "--include-package="
  "--include-package=tensorstore/**"
  "--exclude-package=tensorstore/examples/python/**"
  "--exclude-package=third_party/local_googleapis_imports/**"
  "--exclude-package=third_party/local_opencensus_proto/**"
  "--exclude-package=third_party/local_protoc_gen_validate/**"
  "--exclude-package=third_party/io_bazel_rules_go/**"
  "--exclude-package=third_party/registry/**"
  --ignore-library "//bazel/repo_rules:local_python_runtime.bzl"
  --ignore-library "//docs:doctest.bzl"
  --ignore-library "//bazel:non_compile.bzl"
  --ignore-library "@com_google_protobuf//:protobuf.bzl"
  --ignore-library "@rules_python//python:packaging.bzl"
  --ignore-library "@io_bazel_rules_go//go:deps.bzl"
  --ignore-library "@bazel_features//:deps.bzl"
  --ignore-library "@rules_cc//cc:extensions.bzl"
  --ignore-library "@rules_shell//shell:repositories.bzl"
  --ignore-library "@rules_python//python:repositories.bzl"
  --ignore-library "@rules_python//python/local_toolchains:repos.bzl"
  --ignore-library "@rules_proto//proto:toolchains.bzl"
  --ignore-library "@build_bazel_apple_support//lib:repositories.bzl"
  --ignore-library "@toolchains_llvm//toolchain:rules.bzl"
  --ignore-library "@llvm_toolchain//:toolchains.bzl"
  --bazelrc .bazelrc
  --module bazel_to_cmake.bzl_library.all
)

if(TENSORSTORE_DEBUG_DUMP_TARGETS)
  include(TensorstoreDebugHelpers)
  dump_cmake_targets(${CMAKE_CURRENT_SOURCE_DIR})
endif()
