# CMake Instructions for uninstall
# ================================
# $Id$


# Based on the code from Kitware at
#   http://www.cmake.org/Wiki/CMake_FAQ#Can_I_do_.22make_uninstall.22_with_CMake.3F


IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")
  MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"")
ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt")

FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
STRING(REGEX REPLACE "\n" ";" files "${files}")

#message(STATUS "NOTE: If you have some error messages like \".... does not exist.\" ignore them,
#   it's a harmless bug in the build system")

## KLatexFormula: Some extra files to uninstall

if(UNIX AND NOT KLF_MACOSX_BUNDLES)
  # symbolic links should be removed before the original files or
  # cmake -E remove complains and fails (cmake bug)
  set(files
      "@KLF_ABS_INSTALL_BIN_DIR@/klatexformula_cmdl"
      ${files}
  )
  set(files
      "@KLF_ABS_INSTALL_LIB_DIR@/libklftools.so"
      "@KLF_ABS_INSTALL_LIB_DIR@/libklfbackend.so"
      ${files}
  )
endif()

macro(remove_possibly_empty_directory file)
  # see if we are leaving a directory empty; if so, remove it
  get_filename_component(thedir "${file}" DIRECTORY)
  file(GLOB files_in_thedir "${thedir}/*")
  list(LENGTH files_in_thedir files_in_thedir_len)
  #message("CONSIDERING DIR ${thedir} IN WHICH THERE WAS ${file} ... # of items = ${files_in_thedir_len}: items = ${files_in_thedir}")
  if(files_in_thedir_len EQUAL 0)
    # directory is empty, removing it
    if (EXISTS "${thedir}")
      message(STATUS "Removing directory \"${thedir}\"")
      exec_program(
	"@CMAKE_COMMAND@" ARGS "-E remove_directory \"${thedir}\""
	OUTPUT_VARIABLE rmdir_out
	RETURN_VALUE rmdir_retval
	)
    else()
      set(rmdir_retval 0)
    endif()
    if(NOT "${rmdir_retval}" STREQUAL 0)
      message(FATAL_ERROR "Error uninstalling \"${thedir}\"")
    else()
      # and recurse, because the directory we just removed might have been the
      # last item in its parent directory.
      remove_possibly_empty_directory("${thedir}")
    endif()
  endif()
endmacro()

foreach(file ${files})
  set(file "$ENV{DESTDIR}${file}") # honor $DESTDIR
  if(EXISTS "${file}")
    message(STATUS "Uninstalling \"${file}\"")
    exec_program(
      "@CMAKE_COMMAND@" ARGS "-E remove -f \"${file}\""
      OUTPUT_VARIABLE rm_out
      RETURN_VALUE rm_retval
      )
    if(NOT "${rm_retval}" STREQUAL 0)
      message(FATAL_ERROR "Error uninstalling \"${file}\"")
    endif()
  else()
    if(NOT file MATCHES "__klf_dummy_install_directory__")
      message(STATUS "File \"${file}\" is not installed.")
    endif()
  endif()
  remove_possibly_empty_directory("${file}")
endforeach(file)

