cmake_minimum_required (VERSION 3.2)

include(ExternalProject)
include(GNUInstallDirs)

message("Setting up googletest...")

set(GOOGLETEST_URL "${CMAKE_CURRENT_LIST_DIR}/googletest-release-1.10.0.tar.gz")
set(GOOGLETEST_DIR "${CMAKE_BINARY_DIR}/external_libs/googletest")
#set(GOOGLETEST_INSTALL_DIR "${GOOGLETEST_DIR}/install")

if(DEFINED EXTERNAL_INSTALL_DIR)
  set(GOOGLETEST_INSTALL_DIR ${EXTERNAL_INSTALL_DIR})    
else()
  set(GOOGLETEST_INSTALL_DIR "${GOOGLETEST_DIR}/install")
endif() 

set(GOOGLETEST_CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${GOOGLETEST_INSTALL_DIR})
set(GOOGLETEST_CMAKE_ARGS ${GOOGLETEST_CMAKE_ARGS} -DCMAKE_POSITION_INDEPENDENT_CODE=ON)
set(GOOGLETEST_CMAKE_ARGS ${GOOGLETEST_CMAKE_ARGS} -Dgtest_force_shared_crt=ON)
set(GOOGLETEST_CMAKE_CACHE_ARGS "")
set(GOOGLETEST_PATCH_COMMAND "")

# Set compiler
set(GOOGLETEST_CMAKE_CACHE_ARGS ${GOOGLETEST_CMAKE_CACHE_ARGS} -DCMAKE_C_COMPILER:STRING=${CMAKE_C_COMPILER})
set(GOOGLETEST_CMAKE_CACHE_ARGS ${GOOGLETEST_CMAKE_CACHE_ARGS} -DCMAKE_CXX_COMPILER:STRING=${CMAKE_CXX_COMPILER})

if(UNIX)
	message("Adding GCOV options (GoogleTest)")
	#add_compile_options(-pthread)
	set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread -fprofile-arcs -ftest-coverage")
endif()

if(WIN32)
	if(MINGW)
		set(GOOGLETEST_LIBRARIES ${GOOGLETEST_INSTALL_DIR}/lib/libgtest.a ${GOOGLETEST_INSTALL_DIR}/lib/libgmock.a ${GOOGLETEST_INSTALL_DIR}/lib/libgtest_main.a)
	else()
		set(GOOGLETEST_LIBRARIES 
			optimized ${GOOGLETEST_INSTALL_DIR}/lib/gtest.lib debug ${GOOGLETEST_INSTALL_DIR}/lib/gtestd.lib
			optimized ${GOOGLETEST_INSTALL_DIR}/lib/gmock.lib debug ${GOOGLETEST_INSTALL_DIR}/lib/gmockd.lib
			optimized ${GOOGLETEST_INSTALL_DIR}/lib/gtest_main.lib debug ${GOOGLETEST_INSTALL_DIR}/lib/gtest_maind.lib)
	endif()
else()
	set(GOOGLETEST_LIBRARIES ${GOOGLETEST_INSTALL_DIR}/${CMAKE_INSTALL_LIBDIR}/libgtest.a ${GOOGLETEST_INSTALL_DIR}/${CMAKE_INSTALL_LIBDIR}/libgmock.a ${GOOGLETEST_INSTALL_DIR}/${CMAKE_INSTALL_LIBDIR}/libgtest_main.a)
endif()

ExternalProject_Add(
  googletest-external
  URL ${GOOGLETEST_URL}
  URL_MD5 ecd1fa65e7de707cd5c00bdac56022cd
  DOWNLOAD_DIR ${GOOGLETEST_DIR}/download
  SOURCE_DIR ${GOOGLETEST_DIR}/source
  BINARY_DIR ${GOOGLETEST_DIR}
  INSTALL_DIR ${GOOGLETEST_INSTALL_DIR}
  CMAKE_ARGS "${GOOGLETEST_CMAKE_ARGS}"
  CMAKE_CACHE_ARGS "${GOOGLETEST_CMAKE_CACHE_ARGS}"
  BUILD_BYPRODUCTS ${GOOGLETEST_LIBRARIES}
  UPDATE_COMMAND ""
  PATCH_COMMAND "${GOOGLETEST_PATCH_COMMAND}"
)