include_guard(GLOBAL)
include(FindPackageHandleStandardArgs)

function (ixm_find_package_constructor name)
  set_property(GLOBAL PROPERTY ixm::find ${name})
endfunction()

function (ixm_find_package_destructor)
  get_property(name GLOBAL PROPERTY ixm::find)
  if (NOT TARGET ixm::find::${name})
    return()
  endif()
  aspect(GET path:find AS base-dir)
  dict(SAVE ixm::find::${name} INTO "${base-dir}/${name}.ixm")
  dict(GET ixm::find::${name} REQUIRED required-components)
  foreach (component IN LISTS required-components)
    dict(GET ixm::find::${name} ${component} variables)
    set(found ${name}_${component}_FOUND)
    set(${found} ON)
    foreach (variable IN LISTS variables)
      if (NOT DEFINED ${variable} OR NOT ${variable})
        set(${found} OFF)
        break()
      endif()
    endforeach()
  endforeach()
  dict(GET ixm::find::${name} VARIABLES required-vars)
  if (required-vars)
    list(INSERT required-vars 0 REQUIRED_VARS)
  endif()
  find_package_handle_standard_args(${name}
    ${required-vars}
    VERSION_VAR "${name}_VERSION"
    HANDLE_COMPONENTS)
  set(${name}_FOUND ${${name}_FOUND} PARENT_SCOPE)
endfunction()
