find_package(TINYXML2 CONFIG QUIET)

if(NOT TARGET tinyxml2::tinyxml2)
    if(TINYXML2_FOUND)
        message(STATUS "Found tinyxml2 via config file: ${TINYXML2_DIR}")
        if(NOT TINYXML2_LIBRARY)
            if(TARGET tinyxml2)
                set(TINYXML2_LIBRARY tinyxml2)
            elseif(TARGET tinyxml2::tinyxml2)
                set(TINYXML2_LIBRARY tinyxml2::tinyxml2)
            endif()
        endif()
    else()
        # Try to locate it via pkg-config. If that yields a result, this is
        # considered authoritative. This MUST be done in order to ensure that it
        # works correctly in multi-arch builds.
        find_package(PkgConfig)
        if(PKG_CONFIG_FOUND)
            pkg_check_modules(PC_TINYXML2 QUIET IMPORTED_TARGET GLOBAL tinyxml2)
            if(PC_TINYXML2_FOUND)
                add_library(tinyxml2::tinyxml2 ALIAS PkgConfig::PC_TINYXML2)
            endif()
        endif()

        if(NOT PC_TINYXML2_FOUND)
            find_path(TINYXML2_INCLUDE_DIR NAMES tinyxml2.h)
            find_library(TINYXML2_LIBRARY tinyxml2)
            include(FindPackageHandleStandardArgs)
            find_package_handle_standard_args(TINYXML2 DEFAULT_MSG TINYXML2_LIBRARY TINYXML2_INCLUDE_DIR)
            mark_as_advanced(TINYXML2_INCLUDE_DIR TINYXML2_LIBRARY)
        endif()
    endif()

    if (TINYXML2_FOUND)
        add_library(tinyxml2::tinyxml2 INTERFACE IMPORTED)
        set_target_properties(tinyxml2::tinyxml2 PROPERTIES
            INTERFACE_INCLUDE_DIRECTORIES "${TINYXML2_INCLUDE_DIR}"
            INTERFACE_LINK_LIBRARIES "${TINYXML2_LIBRARY}")
        if(NOT TINYXML2_LIBRARY)
            unset(TINYXML2_LIBRARY CACHE)
        endif()
        if(NOT TINYXML2_INCLUDE_DIR)
            unset(TINYXML2_INCLUDE_DIR CACHE)
        endif()
    endif()
endif()
