#
# This file is licensed under the 3-clause BSD license.
# Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
# See LICENSE.txt for details.
#

macro(target_lib_path target output)
  if(NOT TARGET ${target})
    message(FATAL_ERROR "Cannot determine path of non-existent target")
  endif()

  if(${output})
    unset(${output})
  endif()

  get_target_property(_imported ${target} IMPORTED)
  if(_imported)
    foreach(_build_type Debug;Release;MinSizeRel;RelWithDebInfo)
      string(TOUPPER "${_build_type}" _upper_build_type)
      get_target_property(_path_attempt ${target} IMPORTED_LOCATION_${_upper_build_type})
      if(_path_attempt)
        set(${output} ${_path_attempt})
        break()
      endif()
    endforeach()
    unset(_path_attempt)
    unset(_upper_build_type)

    if(NOT DEFINED ${output})
      get_target_property(_path_attempt ${target} IMPORTED_LOCATION)
      if(_path_attempt)
        set(${output} ${_path_attempt})
        unset(_path_attempt)
      else()
        message(FATAL_ERROR "Could not determine ${target} library filename from IMPORTED_LOCATION")
      endif()
    endif()
  else()
    get_target_property(_output_dir ${target} BINARY_DIR)
    get_target_property(_output_name ${target} OUTPUT_NAME)
    get_target_property(_type ${target} TYPE)
    if(${_type} STREQUAL "SHARED_LIBRARY")
      set(_name "${CMAKE_SHARED_LIBRARY_PREFIX}${_output_name}${CMAKE_SHARED_LIBRARY_SUFFIX}")
    elseif(${_type} STREQUAL "STATIC_LIBRARY")
      set(_name "${CMAKE_STATIC_LIBRARY_PREFIX}${_output_name}${CMAKE_STATIC_LIBRARY_SUFFIX}")
    else()
      message(FATAL_ERROR "Could not determine library filename of in-tree target")
    endif()
    set(${output} ${_output_dir}/${_name})
    unset(_output_dir)
    unset(_output_name)
    unset(_type)
    unset(_name)
  endif()
endmacro()

# Figure out the name of a imported target's filename or the filename of an
# in-tree library target
macro(target_lib_filename target output)
  target_lib_path(${target} _fullpath)
  get_filename_component(${output} ${_fullpath} NAME)
  unset(_fullpath)
endmacro()

# Try to figure out the type of an UNKNOWN_LIBRARY target from its filename
macro(target_lib_type target output)
  get_target_property(${output} ${target} TYPE)
  if(${output} STREQUAL "UNKNOWN_LIBRARY")
    target_lib_path(${target} _fullpath)
    get_filename_component(_extension ${_fullpath} EXT)
    if(${_extension} STREQUAL ${CMAKE_SHARED_LIBRARY_SUFFIX})
      set(${output} "SHARED_LIBRARY")
    elseif(${_extension} STREQUAL ${CMAKE_STATIC_LIBRARY_SUFFIX})
      set(${output} "STATIC_LIBRARY")
    endif()
  endif()
endmacro()

# Figure out the directory where an imported target is and where a target
# built in-tree will be (without generator expressions)
macro(target_lib_directory target output)
  target_lib_path(${target} _fullpath)
  get_filename_component(${output} ${_fullpath} DIRECTORY)
  unset(_fullpath)
endmacro()
