include(FetchContent)

unset(assimp_FOUND)
if (NOT IOS)
    find_package(assimp QUIET)
    message("assimp_FOUND: ${assimp_FOUND}; ASSIMP_FOUND: ${ASSIMP_FOUND}")
endif ()
if (assimp_FOUND OR ASSIMP_FOUND)
    message("Using system assimp")
elseif (ENABLE_ASSIMP)
    message("Building assimp from sources")
    if(NOT DEFINED ASSIMP_REPO)
        set(ASSIMP_REPO https://github.com/assimp/assimp.git)
    endif ()
    FetchContent_Declare(
            assimp
            EXCLUDE_FROM_ALL
            GIT_REPOSITORY ${ASSIMP_REPO}
            GIT_TAG v5.0.1
            GIT_SHALLOW TRUE
    )

    set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
    set(ASSIMP_BUILD_TESTS OFF CACHE BOOL "" FORCE)
    set(ASSIMP_BUILD_SAMPLES OFF CACHE BOOL "" FORCE)
    set(ASSIMP_INJECT_DEBUG_POSTFIX OFF CACHE BOOL "" FORCE)
    set(ASSIMP_INSTALL OFF CACHE BOOL "" FORCE)
    set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE BOOL "" FORCE)
    set(ASSIMP_BUILD_SAMPLES OFF CACHE BOOL "" FORCE)

    FetchContent_MakeAvailable(assimp)

    set(assimp_BUILT ON CACHE INTERNAL "fetched assimp found")
endif ()


function(LinkAssimp TARGET)
    if (NOT assimp_BUILT AND NOT IOS)
        find_package(assimp QUIET)
        message("assimp_FOUND: ${assimp_FOUND}; ASSIMP_FOUND: ${ASSIMP_FOUND}")
        if (assimp_FOUND OR ASSIMP_FOUND)
            set(ASSIMP_LIB_NAME ${ASSIMP_LIBRARIES})
        endif ()
    else ()
        set(ASSIMP_LIB_NAME assimp)
    endif ()
    if (assimp_FOUND OR ASSIMP_FOUND OR assimp_BUILT)
        message("Linking assimp: ${ASSIMP_LIB_NAME}")
        target_link_libraries(${TARGET} PUBLIC ${ASSIMP_LIB_NAME})
    endif ()
endfunction()
