include(Utils)
include(FetchContent)

set(CURL_REPO https://github.com/curl/curl.git)
set(CURL_GIT_TAG curl-8_8_0)

set(CURL_DEPS_INSTALL ${CMAKE_BINARY_DIR}/deps_curl)
find_package(CURL QUIET)
if (NOT ${CURL_FOUND})
    if (NOT WIN32)
        file(MAKE_DIRECTORY ${CURL_DEPS_INSTALL})
        execute_process(
                COMMAND ${CMAKE_COMMAND} -G ${CMAKE_GENERATOR} -DTOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} ${CMAKE_CURRENT_SOURCE_DIR}/ext -DCURL_REPO=${CURL_REPO} -DCURL_GIT_TAG=${CURL_GIT_TAG} -DOPENSSL_REPO=${OPENSSL_REPO} -DPLATFORM=${PLATFORM}
                WORKING_DIRECTORY ${CURL_DEPS_INSTALL}
        )
        execute_process(
                COMMAND ${CMAKE_COMMAND} --build ${CURL_DEPS_INSTALL} --config Release
                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)
    endif ()
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)
        message("Using CURL install dir: ${CURL_DEPS_INSTALL}/INSTALL/include")

        if (APPLE)
            target_link_libraries(${TARGET} PUBLIC curl)
        elseif (WIN32)
            set(CURL_USE_SCHANNEL ON CACHE BOOL "USE SCHANNEL")
            FetchContent_Declare(
                curl
                # In function you cannot access the variables defined outside, so hardcoding for now.
                GIT_REPOSITORY https://github.com/curl/curl.git
                GIT_TAG curl-8_8_0
                GIT_SHALLOW TRUE
                CMAKE_ARGS
                    -DCMAKE_BUILD_TYPE=Release
                    -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_BINARY_DIR}/INSTALL
                    -DUSE_NGHTTP2=OFF
                    -DBUILD_STATIC_LIBS=ON
                    -DBUILD_SHARED_LIBS=OFF
                OVERRIDE_FIND_PACKAGE
            )
            FetchContent_MakeAvailable(curl)
            find_package(curl REQUIRED)
            target_link_libraries(${TARGET} PUBLIC CURL::libcurl)
        else ()
            target_link_libraries(${TARGET} PUBLIC crypto ssl curl)
        endif ()
    else ()
        if (CURL_INCLUDE_DIR)
            target_include_directories(${TARGET} PUBLIC ${CURL_INCLUDE_DIR})
        endif ()
        target_link_libraries(${TARGET} PUBLIC CURL::libcurl)
    endif ()
    target_compile_definitions(${TARGET} PRIVATE HAS_CURL)
endfunction()