include(Utils)

set(CURL_DEPS_INSTALL ${CMAKE_BINARY_DIR}/deps_curl)
find_package(CURL QUIET)
if (NOT ${CURL_FOUND})
    file(MAKE_DIRECTORY ${CURL_DEPS_INSTALL})
    if (WIN32)
        set(EXT_DIR ext_windows)
    else ()
        set(EXT_DIR ext)
    endif ()
    execute_process(
            COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} ${CMAKE_CURRENT_SOURCE_DIR}/${EXT_DIR} -DCURL_REPO=${CURL_REPO} -DOPENSSL_REPO=${OPENSSL_REPO} -DPLATFORM=${PLATFORM}
            WORKING_DIRECTORY ${CURL_DEPS_INSTALL}
    )
    execute_process(
            COMMAND ${CMAKE_COMMAND} --build ${CURL_DEPS_INSTALL}
            RESULT_VARIABLE build_result
    )
    if (NOT ${build_result} EQUAL "0")
        message(FATAL_ERROR "Failed to build curl!")
    endif()

    list(APPEND CMAKE_PREFIX_PATH ${CURL_DEPS_INSTALL}/INSTALL)
else ()
    message("Using system curl")
    set(USING_SYSTEM_CURL ON PARENT_SCOPE)
endif ()

function(LinkCurl TARGET)
    find_package(CURL QUIET)
    if (NOT ${CURL_FOUND})
        set(CURL_DEPS_INSTALL ${CMAKE_BINARY_DIR}/deps_curl)
        target_include_directories(${TARGET} PUBLIC ${CURL_DEPS_INSTALL}/INSTALL/include)
        target_link_directories(${TARGET} PUBLIC ${CURL_DEPS_INSTALL}/INSTALL/lib)

        if (APPLE)
            target_link_libraries(${TARGET} PUBLIC curl)
        elseif (WIN32)
            target_link_libraries(${TARGET} PUBLIC ${OPENSSL_SSL_LIBRARY} ${OPENSSL_CRYPTO_LIBRARY})
        else ()
            target_link_libraries(${TARGET} PUBLIC crypto ssl curl)
        endif ()
    else ()
        target_include_directories(${TARGET} PUBLIC ${CURL_INCLUDE_DIR})
        target_link_libraries(${TARGET} PUBLIC CURL::libcurl)
    endif ()
endfunction()