cmake_minimum_required(VERSION 3.18)
project(pokedaisy_linux C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
# Build only the pinned emulator library, never another platform frontend.
foreach(feature BUILD_QT BUILD_SDL BUILD_GL BUILD_GLES2 BUILD_GLES3 BUILD_SHARED USE_DISCORD_RPC USE_LUA USE_FFMPEG USE_LIBZIP USE_PNG USE_SQLITE3 USE_ELF USE_LZMA USE_DEBUGGERS)
  set(${feature} OFF CACHE BOOL "" FORCE)
endforeach()
set(BUILD_STATIC ON CACHE BOOL "" FORCE)
if(NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../third_party/mgba/CMakeLists.txt")
  message(FATAL_ERROR "Initialize the pinned core: git submodule update --init third_party/mgba")
endif()
add_subdirectory(../third_party/mgba mgba)
find_path(SDL2_INCLUDE_DIR SDL.h PATH_SUFFIXES SDL2 REQUIRED)
find_library(SDL2_LIBRARY NAMES SDL2 REQUIRED)
find_package(Threads REQUIRED)
file(GLOB PD_CORE CONFIGURE_DEPENDS ../3ds/core/*.c)
add_library(pd_linux_common STATIC host_io.c wild.c fly.c flash.c flight.c ../shared/src/commonMain/cpp/pk_flight.c tm_teach.c field_items.c hud.c quick_menu.c ${PD_CORE} ../3ds/desktop/pd_png.c ../shared/src/commonMain/cpp/pk_savevf.c
  ../shared/src/commonMain/cpp/pk_call.c ../shared/src/commonMain/cpp/pk_host.c ../shared/src/commonMain/cpp/pk_wide.c ../shared/src/commonMain/cpp/pk_wide_gb.c
  ../shared/src/commonMain/cpp/pk_rewind.c)
target_include_directories(pd_linux_common PUBLIC ../3ds/core ../third_party/mgba/include ${CMAKE_CURRENT_BINARY_DIR}/mgba/include ${SDL2_INCLUDE_DIR})
target_compile_definitions(pd_linux_common PUBLIC _GNU_SOURCE _POSIX_C_SOURCE=200809L
  USE_PTHREADS) # plorpOS: libmgba is, and pk_rewind.c needs its threaded mCoreRewindContext
target_compile_options(pd_linux_common PRIVATE -Wall -Wextra)
# The app's EXPAND sources, built as they are.
set_source_files_properties(../shared/src/commonMain/cpp/pk_wide.c ../shared/src/commonMain/cpp/pk_wide_gb.c PROPERTIES COMPILE_OPTIONS -Wno-unused-parameter)
target_link_libraries(pd_linux_common PUBLIC mgba ${SDL2_LIBRARY} m Threads::Threads ${CMAKE_DL_LIBS})
# The executable is a libretro frontend: it loads pokedaisy_gba / pokedaisy_gbc / pokedaisy_ds from beside itself and links no
# emulator, only SDL2 and the portable canvas for its menus (3ds/core).
add_library(pd_host_ui STATIC ${PD_CORE} ../3ds/desktop/pd_png.c)
target_include_directories(pd_host_ui PUBLIC ../3ds/core)
target_compile_definitions(pd_host_ui PUBLIC _GNU_SOURCE)
# The library's cover PNGs: zlib's puff (its small inflate), built on its own, without the host's -Werror.
add_library(pd_puff STATIC ../third_party/zlib/contrib/puff/puff.c)
target_include_directories(pd_puff PUBLIC ../third_party/zlib/contrib/puff)
# Zipped ROMs: zlib's inflate, which streams (a DS ROM is too big to unpack in memory).
add_library(pd_inflate STATIC ../third_party/zlib/adler32.c ../third_party/zlib/crc32.c ../third_party/zlib/inffast.c
  ../third_party/zlib/inflate.c ../third_party/zlib/inftrees.c ../third_party/zlib/zutil.c)
# zconf.h: a clean zlib checkout has it; once zlib's own CMake has run in the tree (another core's build) it's renamed
# zconf.h.included. Either is copied into the build tree, so this build never depends on which state the submodule is in.
set(PD_ZLIB_GEN ${CMAKE_CURRENT_BINARY_DIR}/zlib)
file(MAKE_DIRECTORY ${PD_ZLIB_GEN})
set(PD_ZCONF ${CMAKE_CURRENT_SOURCE_DIR}/../third_party/zlib/zconf.h)
if(NOT EXISTS ${PD_ZCONF})
  set(PD_ZCONF ${PD_ZCONF}.included)
endif()
configure_file(${PD_ZCONF} ${PD_ZLIB_GEN}/zconf.h COPYONLY)
target_include_directories(pd_inflate PUBLIC ${PD_ZLIB_GEN} ../third_party/zlib)
# SETTINGS > VERSION: the app's versionName.
file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/../app/build.gradle.kts POCKET_VERSION_LINE REGEX "versionName = ")
string(REGEX MATCH "\"[^\"]+\"" POCKET_VERSION "${POCKET_VERSION_LINE}")
# Bug reports' build number: the app's versionCode.
file(STRINGS ${CMAKE_CURRENT_SOURCE_DIR}/../app/build.gradle.kts POCKET_BUILD_LINE REGEX "versionCode = [0-9]+")
string(REGEX MATCH "[0-9]+" POCKET_BUILD "${POCKET_BUILD_LINE}")
add_executable(pokedaisy-linux main.c library.c bug_report.c cover_png.c rom_zip.c shared_save.c web.c)
if(POCKET_VERSION)
  target_compile_definitions(pokedaisy-linux PRIVATE POCKET_VERSION=${POCKET_VERSION})
endif()
if(POCKET_BUILD)
  target_compile_definitions(pokedaisy-linux PRIVATE POCKET_BUILD=${POCKET_BUILD})
endif()
target_include_directories(pokedaisy-linux PRIVATE
  ../third_party/mgba/src/platform/libretro # libretro.h
  ${SDL2_INCLUDE_DIR})
# PD_HW_RENDER: the GameCube / Wii core (dolphin_libretro.so) draws with OpenGL, so the host gives it a context of its
# own and reads its framebuffer back. Every GL call is loaded through SDL_GL_GetProcAddress, so no GL library is linked.
target_compile_definitions(pokedaisy-linux PRIVATE PD_HW_RENDER=1)
target_compile_options(pokedaisy-linux PRIVATE -Wall -Wextra -Werror)
target_link_libraries(pokedaisy-linux PRIVATE pd_host_ui pd_puff pd_inflate ${SDL2_LIBRARY} m Threads::Threads ${CMAKE_DL_LIBS})
# PC fan games (Pokemon Essentials) on the mkxp-z libretro core, which draws with OpenGL: an offscreen EGL context
# (hw_gl.c). Off by default while it's a spike (docs/specs/pc-fan-games.md).
option(POCKET_PC_GAMES "PC fan games on the mkxp-z core (needs EGL)" OFF)
if(POCKET_PC_GAMES)
  find_library(EGL_LIBRARY NAMES EGL REQUIRED)
  find_package(ZLIB REQUIRED) # pc_png.c: the games' icons
  add_library(pd_pc_companion STATIC pc_companion.c pc_json.c pc_png.c)
  target_link_libraries(pd_pc_companion PUBLIC pd_host_ui ZLIB::ZLIB m)
  target_compile_options(pd_pc_companion PRIVATE -Wall -Wextra)
  target_sources(pokedaisy-linux PRIVATE hw_gl.c pc_mailbox.c pc_state.c)
  target_compile_definitions(pokedaisy-linux PRIVATE POCKET_PC_GAMES)
  # States (512 MB each) go zstd-compressed where libzstd is found, else as they are (pc_state.c).
  find_path(ZSTD_INCLUDE_DIR zstd.h)
  find_library(ZSTD_LIBRARY NAMES zstd)
  if(ZSTD_INCLUDE_DIR AND ZSTD_LIBRARY)
    target_compile_definitions(pokedaisy-linux PRIVATE POCKET_ZSTD)
    target_include_directories(pokedaisy-linux PRIVATE ${ZSTD_INCLUDE_DIR})
    target_link_libraries(pokedaisy-linux PRIVATE ${ZSTD_LIBRARY})
  else()
    message(STATUS "libzstd not found: PC game states are written uncompressed")
  endif()
  target_link_libraries(pokedaisy-linux PRIVATE ${EGL_LIBRARY} pd_pc_companion)
  # Draws the companion's pages from a saved snapshot to PNGs (pc_companion_shot.c).
  add_executable(pc-companion-shot pc_companion_shot.c ../3ds/desktop/pd_png.c)
  target_link_libraries(pc-companion-shot PRIVATE pd_pc_companion)
  # The companion's Ruby preload scripts, built into the binary and installed into the core's Scripts/Preload.
  file(GLOB PC_PRELOADS CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/pc_games/*.rb)
  add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/pc_preloads.h
    COMMAND ${CMAKE_COMMAND} -DOUT=${CMAKE_CURRENT_BINARY_DIR}/pc_preloads.h -DDIR=${CMAKE_CURRENT_SOURCE_DIR}/pc_games
            -P ${CMAKE_CURRENT_SOURCE_DIR}/pc_games/embed.cmake
    VERBATIM
    DEPENDS ${PC_PRELOADS} ${CMAKE_CURRENT_SOURCE_DIR}/pc_games/embed.cmake)
  target_sources(pokedaisy-linux PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/pc_preloads.h)
  target_include_directories(pokedaisy-linux PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
endif()
include(CTest)
option(POCKET_DSPERATE "Optional DSperate Linux backend" OFF)
if(POCKET_DSPERATE)
  enable_language(CXX)
  set(CMAKE_CXX_STANDARD 17)
  include(dsperate/build.cmake)
  set(ds_package_args --dsperate)
endif()
if(BUILD_TESTING)
  add_executable(linux-io-test test_host_io.c)
  add_executable(linux-wild-test test_wild.c)
  foreach(test linux-io-test linux-wild-test)
    target_compile_options(${test} PRIVATE -UNDEBUG -Wall -Wextra -Werror)
    target_link_libraries(${test} PRIVATE pd_linux_common)
    add_test(NAME ${test} COMMAND ${test})
  endforeach()
  add_executable(linux-rom-zip-test test_rom_zip.c rom_zip.c shared_save.c)
  target_compile_options(linux-rom-zip-test PRIVATE -UNDEBUG -Wall -Wextra -Werror)
  target_compile_definitions(linux-rom-zip-test PRIVATE _GNU_SOURCE)
  target_link_libraries(linux-rom-zip-test PRIVATE pd_inflate)
  add_executable(linux-shared-save-test test_shared_save.c shared_save.c)
  target_compile_options(linux-shared-save-test PRIVATE -UNDEBUG -Wall -Wextra -Werror)
  target_compile_definitions(linux-shared-save-test PRIVATE _GNU_SOURCE)
  add_test(NAME shared-save COMMAND linux-shared-save-test)
  # SEND A BUG REPORT's pure parts (its zip, redaction, meta, code): bug_report.c without SDL.
  add_executable(linux-bug-report-test test_bug_report.c bug_report.c)
  target_compile_options(linux-bug-report-test PRIVATE -UNDEBUG -Wall -Wextra -Werror)
  target_compile_definitions(linux-bug-report-test PRIVATE PD_BUG_PURE)
  add_test(NAME bug-report COMMAND linux-bug-report-test ${CMAKE_CURRENT_BINARY_DIR}/bug-report-test.zip)
  find_package(Python3 COMPONENTS Interpreter REQUIRED)
  if(NOT CMAKE_CROSSCOMPILING)
    # The host itself: a crash's note, then a report sent to a stand-in for the endpoint (skipped without curl).
    add_test(NAME bug-report-host COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_bug_report.py $<TARGET_FILE:pokedaisy-linux>)
    set_tests_properties(bug-report-host PROPERTIES SKIP_RETURN_CODE 77)
  endif()
  # A cross build runs the tool through its emulator: from Python it's not started the way CTest starts a test's binary.
  add_test(NAME rom-zip COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_rom_zip.py $<TARGET_FILE:linux-rom-zip-test>
    ${CMAKE_CROSSCOMPILING_EMULATOR})
  add_test(NAME package-smoke COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_package.py $<TARGET_FILE:pokedaisy-linux> ${ds_package_args})
  # No SDL call past 2.0.10 (the old ArkOS's SDL): reads the ELF, so cross builds run it too.
  add_test(NAME sdl-2010-symbols COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_sdl_symbols.py $<TARGET_FILE:pokedaisy-linux>)
  # The launcher starts the binary itself, which a cross build can't without its emulator's sysroot.
  if(NOT CMAKE_CROSSCOMPILING)
    add_test(NAME portmaster-launcher COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_portmaster.py $<TARGET_FILE:pokedaisy-linux>)
  endif()
  add_test(NAME diagnostic-roms COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/make_diagnostic.py)
  set_tests_properties(diagnostic-roms PROPERTIES FIXTURES_SETUP diagnostics)
  set(POCKET_TEST_CORES "" CACHE PATH "Folder with the GB, GBA and DS libretro cores for linux-host-test")
  if(POCKET_TEST_CORES AND NOT CMAKE_CROSSCOMPILING)
    add_test(NAME diagnostic-nds COMMAND ${Python3_EXECUTABLE}
      ${CMAKE_CURRENT_SOURCE_DIR}/dsperate/make_diagnostic.py ${CMAKE_CURRENT_BINARY_DIR}/diagnostic.nds)
    set_tests_properties(diagnostic-nds PROPERTIES FIXTURES_SETUP diagnostics)
    add_test(NAME linux-host-test COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test_host.py
      $<TARGET_FILE:pokedaisy-linux> ${POCKET_TEST_CORES} ${CMAKE_CURRENT_BINARY_DIR})
    set_tests_properties(linux-host-test PROPERTIES FIXTURES_REQUIRED diagnostics TIMEOUT 120)
  endif()
  if(CMAKE_CROSSCOMPILING)
    set(headless offscreen)
  else()
    set(headless dummy)
  endif()
  if(POCKET_TEST_CORES AND NOT CMAKE_CROSSCOMPILING)
    set_tests_properties(linux-host-test PROPERTIES ENVIRONMENT "SDL_VIDEODRIVER=${headless};SDL_AUDIODRIVER=dummy;SDL_RENDER_DRIVER=software")
  endif()
endif()
