cmake_minimum_required(VERSION 3.20)
project(irc_native C)

# Directory with the C sources generated by `python -m ircrecomp lift`.
set(IRC_GEN_DIR "${CMAKE_SOURCE_DIR}/build/gen" CACHE PATH "Generated sources")
set(SDL3_DIR "${CMAKE_SOURCE_DIR}/third_party/SDL3-3.4.16/cmake" CACHE PATH "SDL3 package dir")

if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)
    message(FATAL_ERROR "A 64-bit target is required (the guest address space is a 4 GB window).")
endif()

include(${IRC_GEN_DIR}/sources.cmake)
find_package(SDL3 CONFIG QUIET)
if(NOT SDL3_FOUND)
    # No SDL3 installed (typical on Linux/macOS without dev packages): build it from source.
    include(FetchContent)
    message(STATUS "SDL3 not found, fetching release-3.4.16 from GitHub")
    FetchContent_Declare(SDL3 GIT_REPOSITORY https://github.com/libsdl-org/SDL.git GIT_TAG release-3.4.16 GIT_SHALLOW TRUE)
    set(SDL_SHARED ON CACHE BOOL "" FORCE)
    set(SDL_TEST_LIBRARY OFF CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(SDL3)
endif()

file(GLOB RUNTIME_SOURCES ${CMAKE_SOURCE_DIR}/runtime/*.c)
add_executable(irc WIN32 ${RUNTIME_SOURCES} ${GEN_SOURCES})
target_include_directories(irc PRIVATE ${CMAKE_SOURCE_DIR}/runtime ${IRC_GEN_DIR} ${CMAKE_SOURCE_DIR}/third_party/dr_libs)
target_link_libraries(irc PRIVATE SDL3::SDL3)
set_target_properties(irc PROPERTIES OUTPUT_NAME "IRC")

if(MSVC)
    target_compile_options(irc PRIVATE /MP /bigobj /wd4996 /wd4018 /wd4267)
    set_source_files_properties(${RUNTIME_SOURCES} PROPERTIES COMPILE_OPTIONS "/W3")
    target_compile_definitions(irc PRIVATE _CRT_SECURE_NO_WARNINGS)
    # generated code: favour compile speed of the very large goto-based functions
    set_source_files_properties(${GEN_SOURCES} PROPERTIES COMPILE_OPTIONS "/W0")
else()
    target_compile_options(irc PRIVATE -O2 -fno-strict-aliasing -fwrapv)
    target_link_libraries(irc PRIVATE m)
endif()

if(WIN32 AND TARGET SDL3::SDL3-shared)
    add_custom_command(TARGET irc POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:SDL3::SDL3-shared> $<TARGET_FILE_DIR:irc>)
endif()

# Lossless FLAC encoder for the CD music (used by the ircrecomp pipeline, verified bit-exact)
add_executable(irc_flacenc ${CMAKE_SOURCE_DIR}/tools/flacenc/flacenc.c)

# UTF-8 as the process code page, so paths with accents work with fopen/stat/mkdir
if(WIN32)
    if(MSVC)
        set(IRC_UTF8_RES ${CMAKE_SOURCE_DIR}/runtime/utf8.manifest)   # merged by the MSVC linker
    else()
        set(IRC_UTF8_RES ${CMAKE_SOURCE_DIR}/runtime/utf8.rc)
    endif()
    target_sources(irc PRIVATE ${IRC_UTF8_RES})
    target_sources(irc_flacenc PRIVATE ${IRC_UTF8_RES})
endif()
target_include_directories(irc_flacenc PRIVATE ${CMAKE_SOURCE_DIR}/third_party/dr_libs)
if(MSVC)
    target_compile_options(irc_flacenc PRIVATE /O2 /W3 /wd4996 /wd4267)
endif()
