cmake_minimum_required(VERSION 3.20)
project(base01_b1_foundation LANGUAGES CXX)
if(NOT DEFINED AUDITED_SOURCE OR NOT DEFINED AUDITED_BUILD)
  message(FATAL_ERROR "Supply separate audited source and already-built correctness archives")
endif()
execute_process(COMMAND git -C "${AUDITED_SOURCE}" rev-parse HEAD
  OUTPUT_VARIABLE head OUTPUT_STRIP_TRAILING_WHITESPACE COMMAND_ERROR_IS_FATAL ANY)
if(NOT head STREQUAL "cda9135d36144d4de2771af174e52ac7b30a83c9")
  message(FATAL_ERROR "Audited source SHA mismatch")
endif()
if(CMAKE_CXX_FLAGS MATCHES "flto" OR CMAKE_CXX_FLAGS_RELEASE MATCHES "flto")
  message(FATAL_ERROR "Separate retention translation units require LTO disabled")
endif()
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION OFF)
add_executable(foundation_check native.cpp codec.cpp)
target_include_directories(foundation_check PRIVATE "${AUDITED_SOURCE}/include" "${AUDITED_SOURCE}/tests/cpp")
set(archives)
foreach(lib vm axion isa experimental ffi core)
  if(NOT EXISTS "${AUDITED_BUILD}/libt81_${lib}.a")
    message(FATAL_ERROR "Build audited correctness targets first: missing ${lib}")
  endif()
  list(APPEND archives "${AUDITED_BUILD}/libt81_${lib}.a")
endforeach()
target_link_libraries(foundation_check PRIVATE ${archives} ${archives})
if(UNIX AND NOT APPLE)
  target_link_libraries(foundation_check PRIVATE pthread dl)
endif()
# Bind the executable to the exact native harness files; detect stale binaries.
set(native_fingerprint "")
foreach(name CMakeLists.txt native.cpp codec.cpp codec.hpp)
  set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${name}")
  file(SHA256 "${CMAKE_CURRENT_SOURCE_DIR}/${name}" file_digest)
  string(APPEND native_fingerprint "${name}:${file_digest}\n")
endforeach()
string(SHA256 native_identity "${native_fingerprint}")
file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/foundation_identity.hpp" "#define FOUNDATION_NATIVE_IDENTITY \"${native_identity}\"\n")
target_include_directories(foundation_check PRIVATE "${CMAKE_CURRENT_BINARY_DIR}")
