# Global variables:
# CMU_HOOK_${hook_name}_FUNCTIONS - ordered list of installed hooks

set(CMU_TEMP_DIR "${CMAKE_BINARY_DIR}/_cmake_cmu_tmp/" CACHE INTERNAL "" FORCE)

function(cmu_install_hook hook_name fn)
  if(NOT COMMAND ${fn})
    message(FATAL_ERROR "Tried to install hook with unexisted function/macros: \"${fn}\"")
  endif()
  set(__list ${CMU_HOOK_${hook_name}_FUNCTIONS})
  list(APPEND __list ${fn})
  set(CMU_HOOK_${hook_name}_FUNCTIONS "${__list}" CACHE INTERNAL "" FORCE)
endfunction()

function(cmu_remove_hook hook_name fn)
  if(NOT COMMAND ${fn})
    message(FATAL_ERROR "Tried to remove hook with unexisted function/macros: \"${fn}\"")
  endif()
  set(__list ${CMU_HOOK_${hook_name}_FUNCTIONS})
  list(REMOVE_ITEM __list ${fn})
  set(CMU_HOOK_${hook_name}_FUNCTIONS "${__list}" CACHE INTERNAL "" FORCE)
endfunction()

macro(cmu_call_hooks hook_name)
  #message("Process hook '${hook_name}' functions: '${CMU_HOOK_${hook_name}_FUNCTIONS}' args: '(${ARGN})")
  set(__cmd "(")
  set(__cmd_first_arg "1")
  foreach(a ${ARGN})
    if (NOT DEFINED __cmd_first_arg)
      set(__cmd "${__cmd} ")
    else()
      unset(__cmd_first_arg)
    endif()
    set(__cmd "${__cmd}\"${a}\"")
  endforeach()
  set(__cmd "${__cmd})")
  foreach(fn IN LISTS CMU_HOOK_${hook_name}_FUNCTIONS)
    #message(STATUS "${fn}")
    file(WRITE ${CMU_TEMP_DIR}indirect_call.tmp "${fn}${__cmd}")
    include(${CMU_TEMP_DIR}indirect_call.tmp)
    #file(REMOVE ${CMU_TEMP_DIR}indirect_call.tmp)
  endforeach()
endmacro()  

macro(cmu_call_hooks_reverse hook_name)
  #message("Process hook reverse '${hook_name}' functions: '${CMU_HOOK_${hook_name}_FUNCTIONS}' args: '(${ARGN})")
  set(__cmd "(")
  set(__cmd_first_arg "1")
  foreach(a ${ARGN})
    if (NOT DEFINED __cmd_first_arg)
      set(__cmd "${__cmd} ")
    else()
      unset(__cmd_first_arg)
    endif()
    set(__cmd "${__cmd}\"${a}\"")
  endforeach()
  set(__cmd "${__cmd})")
  set(__hook_list ${CMU_HOOK_${hook_name}_FUNCTIONS})  
  list(REVERSE __hook_list)
  foreach(fn IN LISTS __hook_list)
    #message(STATUS "${fn}")
    file(WRITE ${CMU_TEMP_DIR}indirect_call.tmp "${fn}${__cmd}")
    include(${CMU_TEMP_DIR}indirect_call.tmp)
    #file(REMOVE ${CMU_TEMP_DIR}indirect_call.tmp)
  endforeach()
endmacro()  
