cmake_minimum_required(VERSION 3.21)
project(mag_render_program_compiler LANGUAGES CXX)
find_package(Threads REQUIRED)
find_package(glslang CONFIG REQUIRED)
add_library(mag_render_program_compiler STATIC compiler.cpp)
target_compile_features(mag_render_program_compiler PRIVATE cxx_std_17)
target_link_libraries(mag_render_program_compiler PRIVATE glslang::SPIRV glslang::glslang glslang::glslang-default-resource-limits)
set_target_properties(mag_render_program_compiler PROPERTIES POSITION_INDEPENDENT_CODE ON)
# Export the package's actual transitive library files to Cargo. Do not guess
# whether this machine's glslang package is static or shared, or discard its
# SPIRV-Tools legalization dependency. Reject unfamiliar link expressions.
function(collect_library name)
  string(REGEX REPLACE "^\\$<LINK_ONLY:([^>]+)>$" "\\1" name "${name}")
  if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND name MATCHES "^(rt|m|dl|pthread)$")
    set_property(GLOBAL APPEND PROPERTY MAG_COMPILER_LIBRARIES "system|${name}\n")
    return()
  endif()
  if(NOT TARGET "${name}")
    message(FATAL_ERROR "Unsupported compiler package dependency: ${name}")
  endif()
  get_target_property(kind "${name}" TYPE)
  if(NOT kind STREQUAL "INTERFACE_LIBRARY")
    if(kind STREQUAL "STATIC_LIBRARY")
      set(link_kind static)
    elseif(kind STREQUAL "SHARED_LIBRARY")
      set(link_kind dylib)
    else()
      message(FATAL_ERROR "Unsupported compiler library type: ${kind}")
    endif()
    set_property(GLOBAL APPEND PROPERTY MAG_COMPILER_LIBRARIES "${link_kind}|$<TARGET_LINKER_FILE:${name}>\n")
  endif()
  get_target_property(deps "${name}" INTERFACE_LINK_LIBRARIES)
  if(deps)
    foreach(dep IN LISTS deps)
      if(dep STREQUAL "-pthread")
        set_property(GLOBAL APPEND PROPERTY MAG_COMPILER_LIBRARIES "system|pthread\n")
      else()
        collect_library("${dep}")
      endif()
    endforeach()
  endif()
endfunction()
collect_library(mag_render_program_compiler)
get_property(libraries GLOBAL PROPERTY MAG_COMPILER_LIBRARIES)
string(REPLACE ";" "" libraries "${libraries}")
file(GENERATE OUTPUT "${CMAKE_BINARY_DIR}/libraries-$<CONFIG>.txt" CONTENT "${libraries}")
