include(get_all_targets)

function(clean_clad_targets)
  # iterate through all targets collecting source files
  get_all_targets(all_targets)
  foreach(target ${all_targets})
    get_property(type TARGET ${target} PROPERTY TYPE)
    if(NOT ${type} STREQUAL "INTERFACE_LIBRARY")
      # ignore include only libraries as they have no source files

      get_property(srcs TARGET ${target} PROPERTY SOURCES)
      
      # Instead of adding all sources
      #   list(APPEND all_sources ${srcs})
      # only add sources beneath the path /generated/clad/ because the GLOB is only recursing
      # into this directory any other path will always be disguarded so don't add in the
      # first place.

      foreach(src ${srcs})
        if(${src} MATCHES "/generated/clad/")
          list(APPEND all_sources ${src})
        endif()
      endforeach()
    endif()
  endforeach()

  # iterate through all generated clad files
  # delete any generated clad file that are not used by any target
  file(GLOB_RECURSE EXISTING_GEN_SRCS "${CMAKE_SOURCE_DIR}/generated/clad/*.*")
  foreach(gen_src ${EXISTING_GEN_SRCS})
      if(NOT ${gen_src} MATCHES "Tag.h")
        # ignore special case, *Tag.h that are a by-product of clad generation, quicker than checking the list

        if(NOT ${gen_src} IN_LIST all_sources)
          message("removing ${gen_src} as it is not generated by any current target.")
          file(REMOVE ${gen_src})
        endif()
      endif()
  endforeach()
endfunction()
