cmake_minimum_required(VERSION 3.19)

set(STARE_known_comps static shared)
set(STARE_comp_static NO)
set(STARE_comp_shared NO)
foreach (STARE_comp IN LISTS ${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
    if (STARE_comp IN_LIST STARE_known_comps)
        set(STARE_comp_${STARE_comp} YES)
    else ()
        set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE
            "STARE does not recognize component `${STARE_comp}`.")
        set(${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)
        return()
    endif ()
endforeach ()

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

set(STARE_static_targets "${CMAKE_CURRENT_LIST_DIR}/STARE-static-targets.cmake")
set(STARE_shared_targets "${CMAKE_CURRENT_LIST_DIR}/STARE-shared-targets.cmake")

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

if (STARE_comp_static)
    STARE_load_targets(static)
elseif (STARE_comp_shared)
    STARE_load_targets(shared)
elseif (DEFINED STARE_SHARED_LIBS AND STARE_SHARED_LIBS)
    STARE_load_targets(shared)
elseif (DEFINED STARE_SHARED_LIBS AND NOT STARE_SHARED_LIBS)
    STARE_load_targets(static)
elseif (BUILD_SHARED_LIBS)
    if (EXISTS "${STARE_shared_targets}")
        STARE_load_targets(shared)
    else ()
        STARE_load_targets(static)
    endif ()
else ()
    if (EXISTS "${STARE_static_targets}")
        STARE_load_targets(static)
    else ()
        STARE_load_targets(shared)
    endif ()
endif ()
