if(NOT DEFINED OUTPUT)
    message(FATAL_ERROR "OUTPUT is required")
endif()
if(NOT DEFINED MAIN_LIBRARY)
    message(FATAL_ERROR "MAIN_LIBRARY is required")
endif()
if(DEFINED STATIC_LIBRARIES_FILE)
    file(STRINGS "${STATIC_LIBRARIES_FILE}" STATIC_LIBRARY_LIST)
elseif(DEFINED STATIC_LIBRARIES)
    string(REPLACE "|" ";" STATIC_LIBRARY_LIST "${STATIC_LIBRARIES}")
else()
    message(FATAL_ERROR "STATIC_LIBRARIES or STATIC_LIBRARIES_FILE is required")
endif()

set(BUNDLED_LIBRARY "${OUTPUT}.bundled")
file(REMOVE "${BUNDLED_LIBRARY}")

if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Darwin")
    execute_process(
        COMMAND libtool -static -o "${BUNDLED_LIBRARY}" "${MAIN_LIBRARY}" ${STATIC_LIBRARY_LIST}
        RESULT_VARIABLE BUNDLE_RESULT
        COMMAND_ERROR_IS_FATAL ANY)
elseif(CMAKE_HOST_WIN32)
    execute_process(
        COMMAND "${AR_EXECUTABLE}" "/OUT:${BUNDLED_LIBRARY}" "${MAIN_LIBRARY}" ${STATIC_LIBRARY_LIST}
        RESULT_VARIABLE BUNDLE_RESULT
        COMMAND_ERROR_IS_FATAL ANY)
else()
    set(MRI_SCRIPT "${OUTPUT}.mri")
    file(WRITE "${MRI_SCRIPT}" "CREATE ${BUNDLED_LIBRARY}\n")
    file(APPEND "${MRI_SCRIPT}" "ADDLIB ${MAIN_LIBRARY}\n")
    foreach(STATIC_LIBRARY IN LISTS STATIC_LIBRARY_LIST)
        file(APPEND "${MRI_SCRIPT}" "ADDLIB ${STATIC_LIBRARY}\n")
    endforeach()
    file(APPEND "${MRI_SCRIPT}" "SAVE\nEND\n")
    execute_process(
        COMMAND "${AR_EXECUTABLE}" -M
        INPUT_FILE "${MRI_SCRIPT}"
        RESULT_VARIABLE BUNDLE_RESULT
        COMMAND_ERROR_IS_FATAL ANY)
    file(REMOVE "${MRI_SCRIPT}")
endif()

file(RENAME "${BUNDLED_LIBRARY}" "${OUTPUT}")
if(DEFINED RANLIB_EXECUTABLE AND NOT CMAKE_HOST_WIN32)
    execute_process(COMMAND "${RANLIB_EXECUTABLE}" "${OUTPUT}" COMMAND_ERROR_IS_FATAL ANY)
endif()
