cmake_minimum_required(VERSION 3.19)

set(SomeLib_known_comps static shared)
set(SomeLib_comp_static NO)
set(SomeLib_comp_shared NO)
foreach (SomeLib_comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
    if (SomeLib_comp IN_LIST SomeLib_known_comps)
        set(SomeLib_comp_${SomeLib_comp} YES)
    else ()
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
            "SomeLib does not recognize component `${SomeLib_comp}`.")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
        return()
    endif ()
endforeach ()

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

set(SomeLib_static_targets "${CMAKE_CURRENT_LIST_DIR}/SomeLib-static-targets.cmake")
set(SomeLib_shared_targets "${CMAKE_CURRENT_LIST_DIR}/SomeLib-shared-targets.cmake")

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

if (SomeLib_comp_static)
    SomeLib_load_targets(static)
elseif (SomeLib_comp_shared)
    SomeLib_load_targets(shared)
elseif (DEFINED SomeLib_SHARED_LIBS AND SomeLib_SHARED_LIBS)
    SomeLib_load_targets(shared)
elseif (DEFINED SomeLib_SHARED_LIBS AND NOT SomeLib_SHARED_LIBS)
    SomeLib_load_targets(static)
elseif (BUILD_SHARED_LIBS)
    if (EXISTS "${SomeLib_shared_targets}")
        SomeLib_load_targets(shared)
    else ()
        SomeLib_load_targets(static)
    endif ()
else ()
    if (EXISTS "${SomeLib_static_targets}")
        SomeLib_load_targets(static)
    else ()
        SomeLib_load_targets(shared)
    endif ()
endif ()
