cmake_minimum_required(VERSION 3.22)
project(vice_jni C)

# Auto-detect whether libvice.a was produced by the Gradle buildVice task.
# No manual flag needed — just build the project and Gradle handles the rest.
set(VICE_LIB "${CMAKE_CURRENT_SOURCE_DIR}/vice-libs/${ANDROID_ABI}/libvice.a")
set(VICE_SRC "${CMAKE_CURRENT_SOURCE_DIR}/vice-src")

if(EXISTS "${VICE_LIB}")
    set(HAVE_VICE ON)
    message(STATUS "Found ${VICE_LIB} — building with full VICE emulation")
else()
    set(HAVE_VICE OFF)
    message(STATUS "No libvice.a found — building stub (placeholder framebuffer)")
endif()

# Auto-detect whether libnibtools.a was produced by the Gradle buildNibtools task.
set(NIBTOOLS_LIB "${CMAKE_CURRENT_SOURCE_DIR}/nibtools-libs/${ANDROID_ABI}/libnibtools.a")

if(EXISTS "${NIBTOOLS_LIB}")
    set(HAVE_NIBTOOLS ON)
    message(STATUS "Found ${NIBTOOLS_LIB} — building with disk image download/conversion")
else()
    set(HAVE_NIBTOOLS OFF)
    message(STATUS "No libnibtools.a found — Download Disks feature will be unavailable")
endif()

# ---- JNI wrapper library -------------------------------------------------
add_library(vice_jni SHARED vice_jni.c nibconv_jni.c)

target_link_libraries(vice_jni android log c++_shared z OpenSLES)

if(HAVE_VICE)
    target_compile_definitions(vice_jni PRIVATE HAVE_VICE_SRC=1)
    # Redirect archdep_vice_exit (which calls exit()) to __wrap_archdep_vice_exit
    # in vice_jni.c, which calls pthread_exit() instead of killing the process.
    target_link_options(vice_jni PRIVATE
        -Wl,--wrap=archdep_vice_exit
        -Wl,--wrap=maincpu_mainloop
        -Wl,--wrap=init_main
        -Wl,--wrap=machine_init
        -Wl,--wrap=console_init
        -Wl,--wrap=ui_display_drive_led
        -Wl,--wrap=serial_trap_receive
        -Wl,--wrap=event_snapshot_write_module
        -Wl,--wrap=event_snapshot_read_module
        -Wl,--wrap=machine_trigger_reset
        -Wl,--wrap=machine_reset
        -Wl,--wrap=maincpu_reset)
    target_include_directories(vice_jni PRIVATE
        "${CMAKE_CURRENT_SOURCE_DIR}/vice-libs/${ANDROID_ABI}"
        "${VICE_SRC}/src"
        "${VICE_SRC}/src/arch/headless"
        "${VICE_SRC}/src/arch/shared"
        "${VICE_SRC}/src/c64"
        "${VICE_SRC}/src/drive"
        "${VICE_SRC}/src/lib/p64"
        "${VICE_SRC}/src/lib"
    )
    target_link_libraries(vice_jni "${VICE_LIB}")
endif()

if(HAVE_NIBTOOLS)
    target_compile_definitions(vice_jni PRIVATE HAVE_NIBTOOLS=1)
    # Redirect nibconv's exit() calls (malformed input) to __wrap_exit in
    # nibconv_jni.c, which calls pthread_exit() on the throwaway conversion
    # thread instead of killing the process.
    target_link_options(vice_jni PRIVATE -Wl,--wrap=exit)
    target_link_libraries(vice_jni "${NIBTOOLS_LIB}")
endif()
