cmake_minimum_required(VERSION 3.15)
project(VoidLoader LANGUAGES CXX)

# ============================================================
# Project settings
# ============================================================
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(BUILD_SHARED_LIBS OFF)
include(FetchContent)

add_compile_options(-ffunction-sections -fdata-sections)
add_link_options(-Wl,--gc-sections)
# ============================================================
# Source / includes
# ============================================================
file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS "src/*.cpp")
include_directories(include)

# ============================================================
# Find JDK / JNI / JVMTI
# ============================================================
find_package(Java REQUIRED)
find_package(JNI REQUIRED)
message(STATUS "JNI include dirs: ${JNI_INCLUDE_DIRS}")
message(STATUS "JNI libs:        ${JNI_LIBRARIES}")

# For JVMTI: also include JAVA_HOME/include/<os>
if (DEFINED ENV{JAVA_HOME})
    message(STATUS "JAVA_HOME: $ENV{JAVA_HOME}")
    include_directories($ENV{JAVA_HOME}/include)
    if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
        include_directories($ENV{JAVA_HOME}/include/win32)
    else()
        include_directories($ENV{JAVA_HOME}/include/linux)
    endif()
endif()

FetchContent_Declare(
  VoidLoaderApi
  GIT_REPOSITORY https://git.faumaray.ru/VoidLoader/VoidLoaderApi.git
  GIT_TAG        main # release-1.10.0
)


FetchContent_MakeAvailable(VoidLoaderApi)

# ============================================================
# Platform flags
# ============================================================
if (CMAKE_SYSTEM_NAME STREQUAL "Windows")
    add_definitions(-DWIN32_LEAN_AND_MEAN -DNOMINMAX)
else()
    add_compile_options(-fPIC)
endif()

# ============================================================
# Build shared library
# ============================================================
add_library(${PROJECT_NAME} SHARED ${SOURCES})

target_include_directories(${PROJECT_NAME} PUBLIC ${JNI_INCLUDE_DIRS})
target_link_libraries(${PROJECT_NAME} PUBLIC JNI::JNI JNI::JVM VoidLoaderApiInterface)

if (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
    target_link_options(${PROJECT_NAME} PRIVATE
        -Wl,-z,defs               # no undefined symbols at link
        -Wl,--no-undefined
        -Wl,--as-needed
        -static-libstdc++         # pull libstdc++ into .so
        -static-libgcc            # pull libgcc into .so
        -Wl,-O1
        -Wl,--gc-sections
    )
endif()


# Output name: YourAgent.dll / libYourAgent.so
set_target_properties(${PROJECT_NAME} PROPERTIES
    PREFIX ""
    SUFFIX ".vlmod"
    OUTPUT_NAME "VoidLoader"
)
if(UNIX AND NOT APPLE)
    target_link_options(${PROJECT_NAME} PRIVATE -Wl,--enable-new-dtags -Wl,-rpath,\$ORIGIN)
    set_target_properties(${PROJECT_NAME} PROPERTIES BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN")
endif()
# ============================================================
# Dep bundler (Option B: auto-scan & copy non-system deps)
# ============================================================
set(COPY_DEPS_SCRIPT "${CMAKE_BINARY_DIR}/copy_deps.cmake")
file(WRITE "${COPY_DEPS_SCRIPT}" [=[
cmake_minimum_required(VERSION 3.15)
if(NOT DEFINED ARTIFACT OR NOT DEFINED OUTDIR)
    message(FATAL_ERROR "ARTIFACT and OUTDIR must be set")
endif()

file(MAKE_DIRECTORY "${OUTDIR}")

function(copy_dep path)
    if(NOT EXISTS "${path}")
        return()
    endif()
    string(FIND "${path}" "/lib" sys1)
    string(FIND "${path}" "/usr/lib" sys2)
    if(sys1 EQUAL 0 OR sys2 EQUAL 0)
        return() # skip system libs
    endif()
    get_filename_component(name "${path}" NAME)
    set(dst "${OUTDIR}/${name}")
    if(NOT EXISTS "${dst}")
        file(COPY "${path}" DESTINATION "${OUTDIR}")
        message(STATUS "📦 Copied: ${path} -> ${dst}")
    endif()
endfunction()

if(CMAKE_HOST_UNIX)
    string(REGEX MATCH "\\.dll$" IS_DLL "${ARTIFACT}")
    if(IS_DLL)
        # MinGW DLL
        execute_process(COMMAND objdump -p "${ARTIFACT}" OUTPUT_VARIABLE dump)
        string(REGEX MATCHALL "DLL Name: ([^\r\n]+)" matches "${dump}")
        set(dlls "")
        foreach(m ${matches})
            string(REGEX REPLACE "DLL Name: " "" d "${m}")
            list(APPEND dlls "${d}")
        endforeach()
        list(REMOVE_DUPLICATES dlls)

        set(search_roots
            "/usr/x86_64-w64-mingw32/bin"
            "/usr/lib/gcc/x86_64-w64-mingw32"
        )

        file(GLOB nix "/nix/store/*x86_64-w64-mingw32*")
        foreach(dir ${nix})
            list(APPEND search_roots
                "${dir}/bin"
                "${dir}/sys-root/mingw/bin"
                "${dir}/x86_64-w64-mingw32/sys-root/mingw/bin")
        endforeach()

        foreach(d ${dlls})
            set(found "")
            foreach(root ${search_roots})
                if(EXISTS "${root}")
                    file(GLOB cands "${root}/*")
                    foreach(c ${cands})
                        get_filename_component(n "${c}" NAME)
                        string(TOLOWER "${n}" ln)
                        string(TOLOWER "${d}" ld)
                        if(ln STREQUAL ld)
                            set(found "${c}")
                            break()
                        endif()
                    endforeach()
                endif()
                if(found)
                    break()
                endif()
            endforeach()
            if(found)
                copy_dep("${found}")
            else()
                message(STATUS "⚠️ Missing DLL: ${d}")
            endif()
        endforeach()
    else()
        # Linux ELF
        execute_process(COMMAND ldd "${ARTIFACT}" OUTPUT_VARIABLE out)
        string(REPLACE "\n" ";" lines "${out}")
        foreach(line ${lines})
            string(REGEX MATCH "=> ([/][^ ]+)" m1 "${line}")
            string(REGEX MATCH "^\\s*([/][^ ]+)" m2 "${line}")
            if(m1)
                string(REGEX REPLACE "=> " "" p "${m1}")
                copy_dep("${p}")
            elseif(m2)
                set(p "${m2}")
                copy_dep("${p}")
            endif()
        endforeach()
    endif()
endif()
]=])

add_custom_command(
    TARGET ${PROJECT_NAME} POST_BUILD
    COMMAND ${CMAKE_COMMAND}
        -DARTIFACT=$<TARGET_FILE:${PROJECT_NAME}>
        -DOUTDIR=$<TARGET_FILE_DIR:${PROJECT_NAME}>
        -P "${COPY_DEPS_SCRIPT}"
    COMMENT "Bundling dependent shared libraries next to the artifact"
)