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()

# ---- JNI wrapper library -------------------------------------------------
add_library(vice_jni SHARED vice_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)
    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()
