# cmake/copy_deps_to_exe_dir.cmake
# 用法：
#   cmake -DINPUT="C:/path/to/bin/curl.exe" `
#         -DDIRS="C:/alib/curl/bin;C:/alib/xxx/bin"
#         -P copy_deps_to_exe_dir.cmake `
#
# INPUT
#    需要拷贝依赖的target的路径(不一定是生成物,可以是libcurl.dll等中间物)
# DIRS
#    该target所依赖项存放的目录,因为是命令行,所以无法传列表,请JOIN列表为单一字符串
#    路径之间由__CMAKE_LIST_SEP__作为分隔符进行分割
#
#

message("${Y}==== 进入copy_deps_to_exe_dir.cmake ====${E}")
if (NOT DEFINED INPUT OR NOT EXISTS "${INPUT}")
    message(FATAL_ERROR "INPUT not set or not exists: ${INPUT}")
endif ()


if (NOT DEFINED DIRS)
    message(FATAL_ERROR "DIRS not set: ${DIRS}")
endif ()

message("INPUT=${INPUT}")
cmake_path(GET INPUT PARENT_PATH DESTDIR)
message("DESTDIR=${DESTDIR}")
string(REPLACE "__CMAKE_LIST_SEP__" ";" DIR_PIPE ${DIRS})
message("DIRS=${DIR_PIPE}")  #这是依赖项们所在的目录


# 解析运行时依赖
file(GET_RUNTIME_DEPENDENCIES
        EXECUTABLES "${INPUT}"
        DIRECTORIES ${DIR_PIPE}
        RESOLVED_DEPENDENCIES_VAR _resolved
        UNRESOLVED_DEPENDENCIES_VAR _unresolved

        # 过滤掉系统 DLL（按需增减）
        PRE_EXCLUDE_REGEXES
        "api-ms-win-.*"
        "ext-ms-.*"
        POST_EXCLUDE_REGEXES
        ".*[\\\\/]System32[\\\\/].*"
        ".*[\\\\/]Windows[\\\\/].*"
)

if (_unresolved)
    message(WARNING "Unresolved deps:")
    foreach (d IN LISTS _unresolved)
        message(WARNING "  ${d}")
    endforeach ()
endif ()

# 复制解析到的 DLL
foreach (dll IN LISTS _resolved)
    get_filename_component(dll_name "${dll}" NAME)
    set(dst_file "${DESTDIR}/${dll_name}")

    if (EXISTS "${dst_file}")
        message(STATUS "Skip existing: ${dst_file}")
    else ()
        message(STATUS "Copy: ${dll} \n   --> ${DESTDIR}")
        file(COPY "${dll}" DESTINATION "${DESTDIR}")
    endif ()
endforeach ()
