# Standalone build for the collection's native command-line tools.
#
#   cmake -S tools -B build-tools -G Ninja -DCMAKE_BUILD_TYPE=Release
#   cmake --build build-tools --target disc-ident
#   ./build-tools/disc-ident <image.cue|.bin|.img|.iso|.chd> [--crc] ...
#
# Name the target: libchdr's own CMakeLists.txt does an unconditional
# add_subdirectory(tests) (line 170), so a bare `cmake --build` also links its
# chdr-benchmark sample. That is inherited upstream behaviour - the six game
# builds compile it too - not something introduced here.
#
# WHY THIS PROJECT EXISTS
# -----------------------
# `disc-ident` was previously defined only inside games/dht/CMakeLists.txt
# (lines 35-45), as an EXCLUDE_FROM_ALL target. Building it therefore required
# *configuring the Die Hard Trilogy USA game project*, which includes
# psxrecomp/runtime/runtime.cmake and is driven with -DPSXRECOMP_REQUIRE_GAME_C=ON
# (scripts/build_linux.sh), so it hard-fails when DHT USA's generated guest C is
# absent. A user who owns Alien Trilogy but not Die Hard Trilogy could not build
# the disc importer the launcher's import step depends on. Importing one owned
# edition must not require owning a different one.
#
# This project builds the identical sources, with the identical include path and
# the identical chdr-static dependency, but reaches the CHD decoder through the
# framework's chd_dependency.cmake *alone*:
#
#   * psxrecomp/runtime/chd_dependency.cmake is a top-level module guarded with
#     include_guard(GLOBAL) (line 1). Its only sibling include is
#     psxrecomp/cmake/psx_dependency_archive.cmake (line 4), and it is the only
#     thing in the tree that brings in libchdr — which is what actually defines
#     the chdr-static target (libchdr's own CMakeLists.txt:113).
#   * runtime.cmake pulls that very module at runtime.cmake:12, so the
#     chdr-static built here is the same pinned libchdr revision, configured
#     with the same forced options, that the six game runtimes link.
#   * Nothing else from runtime.cmake is included. No SDL3, no game.toml, no
#     generated guest C, no PSXRECOMP_REQUIRE_GAME_C, no per-edition state.
#
# The vendored-archive / offline behaviour is inherited unchanged: set
# -DPSX_DEPS_OFFLINE=ON to forbid downloads (psx_dependency_archive.cmake:41),
# or -DPSX_THIRD_PARTY_DIR=<dir> to point at another framework's third_party/.
#
# This file is platform-neutral. It does not replace the Windows build path:
# games/dht/CMakeLists.txt still defines its own `disc-ident` target, and
# scripts/build.ps1 / package_release.ps1 keep working exactly as before.

cmake_minimum_required(VERSION 3.20)
project(PSXTrilogyRecompTools LANGUAGES C CXX)

# Match runtime.cmake's behaviour: an unspecified build type otherwise means
# -O0, and these tools hash whole disc images.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    set(CMAKE_BUILD_TYPE Release CACHE STRING
        "Build type (Release/RelWithDebInfo/Debug)" FORCE)
    message(STATUS "psx-tools: no CMAKE_BUILD_TYPE set - defaulting to Release")
endif()

# ---------------------------------------------------------------------------
# Locate the framework. Default is the sibling checkout; override for an
# out-of-tree or relocated framework, which is why runtime.cmake is not assumed
# to have already set this.
# ---------------------------------------------------------------------------
if(NOT PSXRECOMP_ROOT)
    get_filename_component(_psx_tools_default_root
        "${CMAKE_CURRENT_SOURCE_DIR}/../psxrecomp" ABSOLUTE)
    set(PSXRECOMP_ROOT "${_psx_tools_default_root}" CACHE PATH
        "Path to the pinned psxrecomp framework checkout")
    unset(_psx_tools_default_root)
endif()

if(NOT EXISTS "${PSXRECOMP_ROOT}/runtime/chd_dependency.cmake")
    message(FATAL_ERROR
        "psx-tools: no psxrecomp framework at ${PSXRECOMP_ROOT}\n"
        "  Expected ${PSXRECOMP_ROOT}/runtime/chd_dependency.cmake\n"
        "  Restore the checkout pinned in framework_pins.json, or configure "
        "with -DPSXRECOMP_ROOT=<path to psxrecomp>.")
endif()

# The ONLY framework CMake this project includes. Deliberately not runtime.cmake.
include("${PSXRECOMP_ROOT}/runtime/chd_dependency.cmake")

if(NOT TARGET chdr-static)
    message(FATAL_ERROR
        "psx-tools: chd_dependency.cmake did not provide the chdr-static "
        "target. The pinned libchdr archive is missing or failed to configure; "
        "stage it with psxrecomp/tools/ci/vendor_deps.sh psx_libchdr.")
endif()

# ---------------------------------------------------------------------------
# disc-ident: identify a PS1 disc image and optionally extract its boot
# executable. Prints one JSON object; used by the collection launcher's disc
# import step. Source list mirrors games/dht/CMakeLists.txt:35-45 exactly.
# ---------------------------------------------------------------------------
set(PSX_DISC_IDENT_SOURCES
    "${CMAKE_CURRENT_SOURCE_DIR}/disc_ident.cpp"
    "${PSXRECOMP_ROOT}/runtime/src/disc_identity.cpp"
    "${PSXRECOMP_ROOT}/runtime/src/disc_path.cpp"
    "${PSXRECOMP_ROOT}/runtime/src/cue_sheet.cpp"
    "${PSXRECOMP_ROOT}/runtime/src/iso_reader.cpp"
    "${PSXRECOMP_ROOT}/runtime/src/crc32.c"
    "${PSXRECOMP_ROOT}/runtime/src/psx_sha256.c")

foreach(_psx_tools_source IN LISTS PSX_DISC_IDENT_SOURCES)
    if(NOT EXISTS "${_psx_tools_source}")
        message(FATAL_ERROR "psx-tools: missing source ${_psx_tools_source}")
    endif()
endforeach()
unset(_psx_tools_source)

add_executable(disc-ident ${PSX_DISC_IDENT_SOURCES})
target_include_directories(disc-ident PRIVATE "${PSXRECOMP_ROOT}/runtime/include")
target_link_libraries(disc-ident PRIVATE chdr-static)

# disc_identity.cpp / cue_sheet.cpp / disc_ident.cpp use std::filesystem. The
# game project relies on the compiler defaulting to gnu++17; state it instead so
# this project does not silently depend on a GCC default.
target_compile_features(disc-ident PRIVATE cxx_std_17)

# Keep the binary at the top of the build directory regardless of generator, so
# packaging and the launcher can name one predictable path.
set_target_properties(disc-ident PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
    RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}"
    RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}"
    RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}")

# ---------------------------------------------------------------------------
# Link mode.
#
# The game project's copy applies `-static` unconditionally
# (games/dht/CMakeLists.txt:45). That is fine for MinGW, but on Linux a fully
# static glibc link is not universally available (no libc.a installed) and is
# not universally safe: static glibc still dlopens NSS modules for user/host
# lookups, so a statically linked binary that calls getpwnam/getaddrinfo can
# fail at runtime on a machine whose NSS build differs.
#
# disc-ident opens files and hashes bytes - no name service, no dlopen, no
# locale plugins - so `-static` is genuinely safe *for this tool*. Rather than
# assume the toolchain can produce it, PROBE it: link a real test program with
# std::filesystem and std::ifstream under -static and use the flag only if that
# actually links. Otherwise fall back to -static-libstdc++ -static-libgcc, which
# removes the dependency on the *build machine's* GCC runtime (the part that
# actually breaks when a tool built on one distro is run on another) while
# leaving glibc dynamic.
#
#   -DPSX_TOOLS_STATIC=OFF               no static flags at all (plain dynamic)
#   -DPSX_TOOLS_FULL_STATIC_LINKS=OFF    skip the -static probe, take the
#                                        -static-libstdc++ fallback
#
# Note for the packager: passing this probe means the toolchain produced a
# static ELF for this tool. It is NOT a claim that the collection's runtimes
# can be, or are, statically linked - they cannot be; they need SDL3, OpenGL
# and dlopen.
# ---------------------------------------------------------------------------
option(PSX_TOOLS_STATIC
    "Fully static-link disc-ident when the toolchain actually supports it" ON)

set(PSX_TOOLS_LINK_MODE "toolchain default")
if(MSVC)
    if(PSX_TOOLS_STATIC)
        set_property(TARGET disc-ident PROPERTY
            MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
        set(PSX_TOOLS_LINK_MODE "static MSVC runtime (/MT)")
    endif()
elseif(PSX_TOOLS_STATIC)
    include(CheckCXXSourceCompiles)
    set(_psx_tools_probe [[
        #include <filesystem>
        #include <fstream>
        #include <string>
        int main() {
            std::filesystem::path p("probe.bin");
            std::ifstream f(p, std::ios::binary);
            std::string s = p.string();
            return (int)s.size() & 0;
        }
    ]])

    set(CMAKE_REQUIRED_LINK_OPTIONS -static)
    check_cxx_source_compiles("${_psx_tools_probe}" PSX_TOOLS_FULL_STATIC_LINKS)
    set(CMAKE_REQUIRED_LINK_OPTIONS "")

    if(PSX_TOOLS_FULL_STATIC_LINKS)
        target_link_options(disc-ident PRIVATE -static)
        set(PSX_TOOLS_LINK_MODE "fully static (-static, probe linked)")
    else()
        set(CMAKE_REQUIRED_LINK_OPTIONS -static-libstdc++ -static-libgcc)
        check_cxx_source_compiles("${_psx_tools_probe}" PSX_TOOLS_STATIC_CXX_LINKS)
        set(CMAKE_REQUIRED_LINK_OPTIONS "")
        if(PSX_TOOLS_STATIC_CXX_LINKS)
            target_link_options(disc-ident PRIVATE -static-libstdc++ -static-libgcc)
            set(PSX_TOOLS_LINK_MODE
                "static libstdc++/libgcc, dynamic libc (-static unavailable)")
        else()
            set(PSX_TOOLS_LINK_MODE
                "toolchain default (neither -static nor -static-libstdc++ linked)")
        endif()
    endif()
    unset(_psx_tools_probe)
endif()

message(STATUS "psx-tools: framework   ${PSXRECOMP_ROOT}")
message(STATUS "psx-tools: disc-ident link mode: ${PSX_TOOLS_LINK_MODE}")

# Optional, for packagers staging the tool next to the runtimes.
include(GNUInstallDirs)
install(TARGETS disc-ident RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
