# SPDX-License-Identifier: GPL-3.0-or-later
#
# Lift the NSOs of the user's dump and build one static library per module. Everything game-specific (id, modules, load addresses,
# translation units) comes from game.toml in this folder.
#
#   scriptsuild_game.cmd pkp                  (configure + build into workuild\pkp; NX_ROOT is the repository root)
#
# Inputs (read-only): <root>\game\exefs\<module files>. Generated C++ goes to <root>\work\lift\<module>, build output to
# workuild\<id>: neither is ever committed. Targets: <id>_<module> (static libraries, each provides `nxmod_<name>`: ctx.h
# NxModule), and `<id>_modules` builds all of them.
cmake_minimum_required(VERSION 3.25)
include("${CMAKE_CURRENT_LIST_DIR}/../../cmake/GameManifest.cmake")
game_manifest_load("${CMAKE_CURRENT_LIST_DIR}/game.toml")
project(${GM_ID}_lift C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include("${CMAKE_CURRENT_LIST_DIR}/../../cmake/NxRecomp.cmake")

string(TOUPPER "${GM_ID}" _G)
get_filename_component(_ROOT_DEFAULT "${CMAKE_CURRENT_LIST_DIR}/../../../.." ABSOLUTE)   # the project root (nx/ is the engine clone inside it)
set(${_G}_ROOT "${_ROOT_DEFAULT}" CACHE PATH "repository root (game/, work/)")
if(DEFINED NX_ROOT)
    get_filename_component(${_G}_ROOT "${NX_ROOT}/.." ABSOLUTE)
    set(${_G}_ROOT "${${_G}_ROOT}" CACHE PATH "project root (game/, work/)" FORCE)
endif()
set(${_G}_EXEFS "${${_G}_ROOT}/game/dump/exefs" CACHE PATH "folder with the NSOs of the game")
set(${_G}_GEN "${${_G}_ROOT}/work/lift" CACHE PATH "where the generated sources go")
# translation units per module: about 45k instructions each (docs/S1b.md)
math(EXPR _last "${GM_MODULE_COUNT} - 1")
foreach(_i RANGE ${_last})
    set(_m "${GM_module_${_i}_name}")
    string(TOUPPER "${_m}" _M)
    set(${_G}_SHARDS_${_M} ${GM_module_${_i}_units} CACHE STRING "translation units of ${_m}")
    set(_sites "")
    if(DEFINED GM_module_${_i}_sites)
        set(${_G}_SITES "${CMAKE_CURRENT_LIST_DIR}/${GM_module_${_i}_sites}" CACHE FILEPATH "hook sites of ${_m} for this build (resolved from sites.sig)")
        set(_sites SITES "${${_G}_SITES}")
    endif()
    nxrecomp_add_module(${GM_ID}_${_m} INPUT "${${_G}_EXEFS}/${GM_module_${_i}_file}" NAME ${_m} INDEX ${GM_module_${_i}_index}
                        BASE ${GM_module_${_i}_base} GAME ${GM_ID} SHARDS ${${_G}_SHARDS_${_M}}
                        ${_sites} OUTDIR "${${_G}_GEN}/${_m}")
endforeach()
add_custom_target(${GM_ID}_modules DEPENDS ${GM_MODULE_LIBS})

# Link check (target <id>_link_check): the module libraries plus stubs for what the runtime provides. Proves every symbol resolves.
add_executable(${GM_ID}_link_check EXCLUDE_FROM_ALL ../mpr/link_check.cpp)
target_link_libraries(${GM_ID}_link_check PRIVATE ${GM_MODULE_LIBS})
target_compile_options(${GM_ID}_link_check PRIVATE /w /EHs-c- /GR-)
