# Adapated from ITKv4/CMake/PreventInSourceBuilds.cmake
#
# This function will prevent in-source builds
function(AssureOutOfSourceBuilds PROJECT_NAME)
  # make sure the user doesn't play dirty with symlinks
  get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
  get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH)

  # disallow in-source builds
  if("${srcdir}" STREQUAL "${bindir}")
    message("###########################################################################")
    message("# ${PROJECT_NAME} should not be configured & built in the ${PROJECT_NAME} source directory")
    message("# You must run cmake in a build directory.")
    message("# For example:")
    message("#")
    message("#     mkdir ${PROJECT_NAME}-Sandbox ; cd ${PROJECT_NAME}-sandbox")
    message("#")
    message("# Check out source code in ${PROJECT_NAME}-sandbox")
    message("#")
    message("#     mkdir ${PROJECT_NAME}-build")
    message("#")
    message("# this will create the following directory structure")
    message("#")
    message("# ${PROJECT_NAME}-Sandbox")
    message("#  +--${PROJECT_NAME}")
    message("#  +--${PROJECT_NAME}-build")
    message("#")
    message("# Then you can proceed to configure and build")
    message("# by using the following commands")
    message("#")
    message("#     cd ${PROJECT_NAME}-build")
    message("#     cmake ../${PROJECT_NAME} # or ccmake, or cmake-gui")
    message("#     make")
    message("#")
    message("# NOTE: Given that you already tried to make an in-source build")
    message("#       CMake have already created several files & directories")
    message("#       in your source tree.")
    message("#")
    message("# The following command will show you all files not part of ${PROJECT_NAME}")
    message("#       cd ${PROJECT_NAME}-Sandbox/${PROJECT_NAME}")
    message("#       svn status | grep '[^?]' | awk '{print \$2}'")
    message("#")
    message("# WARNING: if you have added files to ${PROJECT_NAME} but not used svn add")
    message("# to add them to SVN's version control, this command will display them")
    message("# along with the files CMake created during configuration.  You will need")
    message("# to either save them outside the ${PROJECT_NAME} source tree, or run svn add")
    message("# to let SVN know they are legitimate source files.")
    message("# Once you've verified that all unknown files are the result of CMake")
    message("# configuration, you can run this command to clean them up")
    message("#       svn status | grep '[^?]' | awk '{print \$2}' | xargs rm -fr")
    message("###########################################################################")
    message(FATAL_ERROR "Quitting configuration")
  endif()
endfunction()

AssureOutOfSourceBuilds(${CMAKE_PROJECT_NAME})
