cmake_minimum_required(VERSION 3.15)

set(tinyxml2_known_comps static shared)
set(tinyxml2_comp_static NO)
set(tinyxml2_comp_shared NO)
foreach (tinyxml2_comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
    if (tinyxml2_comp IN_LIST tinyxml2_known_comps)
        set(tinyxml2_comp_${tinyxml2_comp} YES)
    else ()
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
            "tinyxml2 does not recognize component `${tinyxml2_comp}`.")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
        return()
    endif ()
endforeach ()

if (tinyxml2_comp_static AND tinyxml2_comp_shared)
    set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
        "tinyxml2 `static` and `shared` components are mutually exclusive.")
    set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
    return()
endif ()

set(tinyxml2_static_targets "${CMAKE_CURRENT_LIST_DIR}/tinyxml2-static-targets.cmake")
set(tinyxml2_shared_targets "${CMAKE_CURRENT_LIST_DIR}/tinyxml2-shared-targets.cmake")

macro(tinyxml2_load_targets type)
    if (NOT EXISTS "${tinyxml2_${type}_targets}")
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
            "tinyxml2 `${type}` libraries were requested but not found.")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
        return()
    endif ()
    include("${tinyxml2_${type}_targets}")
endmacro()

if (tinyxml2_comp_static)
    tinyxml2_load_targets(static)
elseif (tinyxml2_comp_shared)
    tinyxml2_load_targets(shared)
elseif (DEFINED tinyxml2_SHARED_LIBS AND tinyxml2_SHARED_LIBS)
    tinyxml2_load_targets(shared)
elseif (DEFINED tinyxml2_SHARED_LIBS AND NOT tinyxml2_SHARED_LIBS)
    tinyxml2_load_targets(static)
elseif (BUILD_SHARED_LIBS)
    if (EXISTS "${tinyxml2_shared_targets}")
        tinyxml2_load_targets(shared)
    else ()
        tinyxml2_load_targets(static)
    endif ()
else ()
    if (EXISTS "${tinyxml2_static_targets}")
        tinyxml2_load_targets(static)
    else ()
        tinyxml2_load_targets(shared)
    endif ()
endif ()
