cmake_minimum_required(VERSION 3.5)

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()

file(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")
foreach(file ${files})
  message(STATUS "Uninstalling \"${file}\"")
  if(EXISTS "${file}")
    execute_process(COMMAND
      "@CMAKE_COMMAND@" -E remove "${file}"
      OUTPUT_VARIABLE rm_out
      RESULT_VARIABLE rm_retval
      )
    if(NOT "${rm_retval}" STREQUAL 0)
      message(FATAL_ERROR "Problem when removing \"${file}\": ${rm_out}")
    endif()
  else()
    message(STATUS "File \"${file}\" does not exist.")
  endif()
  get_filename_component(path ${file} DIRECTORY)

  # Remove include/grantlee lib/grantlee/${version} and lib/grantlee if no other
  # versions are present.
  while( ${path} MATCHES ".*grantlee.*" )
    file(GLOB contents RELATIVE ${path} "${path}/*" )
    if (NOT contents)
      message(STATUS "Removing empty directory: ${path}")

      execute_process(COMMAND
        "@CMAKE_COMMAND@" -E remove_directory "${path}"
        OUTPUT_VARIABLE rm_out
        RESULT_VARIABLE rm_retval
      )

      if("${rm_retval}" STREQUAL 0)
        get_filename_component(path ${path} DIRECTORY)
      else()
        message(FATAL_ERROR "Problem when removing \"${path}\"")
      endif()
    else()
      break()
    endif()
  endwhile()
endforeach()
