# Builder (IB06): disc -> recompiled C++ -> native Illbleed.exe on the user's machine.
if(WIN32)
    add_library(ib_builder_core STATIC builder_core.cpp portable_compiler.cpp "${PROJECT_SOURCE_DIR}/tools/extractor/util/hash.cpp")
    target_include_directories(ib_builder_core PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}"
                               PRIVATE "${PROJECT_SOURCE_DIR}/tools/extractor")
    target_link_libraries(ib_builder_core PUBLIC ib_legacy_boot PRIVATE urlmon)
    file(TO_CMAKE_PATH "${PROJECT_SOURCE_DIR}" _ib_source)
    target_compile_definitions(ib_builder_core PRIVATE UNICODE _UNICODE NOMINMAX
        IB_SOURCE_DIR="${_ib_source}" IB_RECOMP_PATH="$<TARGET_FILE:ib-recomp>")
    add_dependencies(ib_builder_core ib-recomp)
    add_executable(ib-builder main_cli.cpp)
    target_link_libraries(ib-builder PRIVATE ib_builder_core)
    add_executable(Illbleed-Recompiler WIN32 main_gui.cpp)
    target_compile_definitions(Illbleed-Recompiler PRIVATE UNICODE _UNICODE NOMINMAX)
    target_link_libraries(Illbleed-Recompiler PRIVATE ib_builder_core comctl32 ole32 shell32)
endif()

set(IB_STANDALONE_INPUT "" CACHE FILEPATH "Programa SH-4 binário para o Builder")
set(IB_STANDALONE_BASE "1000" CACHE STRING "Endereço de carga hexadecimal")
set(IB_STANDALONE_ENTRY "1000" CACHE STRING "Endereço de entrada hexadecimal")
if(NOT IB_STANDALONE_INPUT)
    return()
endif()

get_filename_component(_input "${IB_STANDALONE_INPUT}" ABSOLUTE BASE_DIR "${PROJECT_SOURCE_DIR}")
if(NOT EXISTS "${_input}" OR IS_DIRECTORY "${_input}")
    message(FATAL_ERROR "IB_STANDALONE_INPUT deve apontar para um arquivo binário SH-4")
endif()

set(_generated "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>/standalone.cpp")
set(_settings "${CMAKE_CURRENT_BINARY_DIR}/standalone-settings.txt")
file(CONFIGURE OUTPUT "${_settings}"
    CONTENT "@_input@\n@IB_STANDALONE_BASE@\n@IB_STANDALONE_ENTRY@\n" @ONLY)
add_custom_command(
    OUTPUT "${_generated}"
    COMMAND "${CMAKE_COMMAND}" -E make_directory "${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG>"
    COMMAND ib-sh4-aot --input "${_input}" --base "${IB_STANDALONE_BASE}"
            --entry "${IB_STANDALONE_ENTRY}" --standalone --output "${_generated}"
    DEPENDS ib-sh4-aot "${_input}" "${_settings}"
    VERBATIM)
add_executable(ib-standalone "${_generated}")
target_link_libraries(ib-standalone PRIVATE ib_sh4_aot_host)
install(TARGETS ib-standalone RUNTIME DESTINATION bin COMPONENT Standalone)
