include(ExternalProject)

#
#
#

if(NOT DEFINED QEVERSION)
   message(FATAL_ERROR "Set QEVERSION to either 6.2.1 or 6.3")
endif()

if(DEFINED QEFILES)
  set(QELIBRARY_ZIP_PATH ${QEFILES})
else()
  set(QELIBRARY_ZIP_PATH https://github.com/QEF/q-e/archive/qe-${QEVERSION}.zip)
endif()

#if(NOT DEFINED QEFILES)
#  message(FATAL_ERROR "QEFILES is not set, please set it to the downloaded zip file containing the QE program")
#endif()
#
#if(NOT DEFINED QEFILES)
#  message(FATAL_ERROR "QEFILES is not set, please set it to the downloaded zip file containing the QE program")
#endif()
#
#set(QELIBRARY_ZIP_PATH "${CMAKE_CURRENT_SOURCE_DIR}/${QEFILES}")
#if(NOT DEFINED QEPATCH)
#   message(FATAL_ERROR "QEPATCH is not set, please choose either qe-6.2.1_to_pimdlib.patch_template or  qe-6.3_to_pimdlib.patch_template")
#endif()

file(READ qe-${QEVERSION}_to_pimdlib.patch_template QEPATCHCONTENTS)
string(REPLACE "CMAKEBUILDDIR" "${CMAKE_BINARY_DIR}" MODIFIEDQEPATCHCONTENTS "${QEPATCHCONTENTS}")
file(WRITE qe-cmake.patch "${MODIFIEDQEPATCHCONTENTS}")


ExternalProject_Add(
	qe_lib
	URL ${QELIBRARY_ZIP_PATH}
	PREFIX ${CMAKE_BINARY_DIR}/qe_lib
	PATCH_COMMAND patch -p1 < ${CMAKE_CURRENT_SOURCE_DIR}/qe-cmake.patch
	WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/qe_lib/src/qe_lib/
	CONFIGURE_COMMAND ${CMAKE_BINARY_DIR}/qe_lib/src/qe_lib/configure
	BUILD_COMMAND make pw
	BUILD_IN_SOURCE 1
	INSTALL_COMMAND ""
	DEPENDS CommonVars
)
