include(Utils)

find_package(LibArchive QUIET)
if (NOT LibArchive_FOUND)
    file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/deps)
    execute_process(
            COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DCMAKE_TOOLCHAIN_FILE=${TOOLCHAIN} -DPLATFORM=${PLATFORM} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DZLIB_REPO=${ZLIB_REPO} -DZSTD_REPO=${ZSTD_REPO} -DLZ4_REPO=${LZ4_REPO} -DLIBARCHIVE_REPO=${LIBARCHIVE_REPO}
            WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/deps
    )
    execute_process(
            COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR}/deps --config Release
            RESULT_VARIABLE build_result
    )
    if (NOT ${build_result} EQUAL "0")
        message(FATAL_ERROR "Failed to build lib archive!")
    endif()
else ()
    message("Using system LibArchive")
endif ()

function(LinkLibArchive TARGET)
    list(APPEND CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR}/deps/INSTALL)
    find_package(LibArchive REQUIRED)
    if (IOS)
        set(LibArchive_LIBRARIES ${CMAKE_BINARY_DIR}/deps/INSTALL/lib/libarchive.a)
    endif()
    set(ZLIB_USE_STATIC_LIBS ON)
    find_package(ZLIB REQUIRED)
    find_package(zstd REQUIRED)
    find_package(LZ4 QUIET)
    find_package(BZip2 QUIET)
    find_package(LibLZMA QUIET)
    find_package(LibXml2 QUIET)
    find_package(EXPAT QUIET)
    target_include_directories(${TARGET} PUBLIC ${LibArchive_INCLUDE_DIR})
    target_link_libraries(${TARGET} PUBLIC ${LibArchive_LIBRARIES} ${ZLIB_LIBRARIES} ${zstd_LIBRARIES} ${LZ4_LIBRARIES})

    if (BZIP2_LIBRARIES)
        target_link_libraries(${TARGET} PUBLIC ${BZIP2_LIBRARIES})
    endif()
    if (LIBLZMA_LIBRARIES)
        target_link_libraries(${TARGET} PUBLIC ${LIBLZMA_LIBRARIES})
    endif()
    if (LibXml2_FOUND)
    	target_link_libraries(${TARGET} PUBLIC ${LIBXML2_LIBRARIES})
    endif()
    if (EXPAT_FOUND)
    	target_link_libraries(${TARGET} PUBLIC ${EXPAT_LIBRARIES})
    endif()
endfunction()
