cmake_minimum_required(VERSION 3.15)

include(FetchContent)

FetchContent_Declare(
  libQGLViewer_sources
  URL http://www.libqglviewer.com/src/libQGLViewer-2.7.2.tar.gz
  URL_HASH MD5=a9d965d1ce41f7db6b34f440bb74f061)

FetchContent_MakeAvailable(libQGLViewer_sources)
FetchContent_GetProperties(
  libQGLViewer_sources
  SOURCE_DIR libQGLViewer_SOURCE_DIR
  BINARY_DIR libQGLViewer_BINARY_DIR)

find_program(QMAKE qmake)
execute_process(
  WORKING_DIRECTORY ${libQGLViewer_BINARY_DIR}
  COMMAND "${QMAKE}" "${libQGLViewer_SOURCE_DIR}/QGLViewer/QGLViewer.pro"
  COMMAND_ECHO STDERR
  OUTPUT_VARIABLE QGLVIEWER_CFG_OUT
  ERROR_VARIABLE QGLVIEWER_CFG_OUT
  ECHO_OUTPUT_VARIABLE
  ECHO_ERROR_VARIABLE
  RESULT_VARIABLE QGLVIEWER_CFG_RES)
message("QGLViewer configuration result: ${QGLVIEWER_CFG_RES}")

find_program(MAKE make)
include(ProcessorCount)
ProcessorCount(NCORES)
execute_process(
  WORKING_DIRECTORY ${libQGLViewer_BINARY_DIR}
  COMMAND "${MAKE}" "-j${NCORES}"
  COMMAND_ECHO STDERR
  OUTPUT_VARIABLE QGLVIEWER_BUILD_OUT
  ERROR_VARIABLE QGLVIEWER_BUILD_OUT
  ECHO_OUTPUT_VARIABLE
  ECHO_ERROR_VARIABLE
  RESULT_VARIABLE QGLVIEWER_BUILD_RES)
message("QGLViewer build result: ${QGLVIEWER_BUILD_RES}")

add_library(libQGLViewer INTERFACE)

target_include_directories(libQGLViewer INTERFACE ${libQGLViewer_SOURCE_DIR})

# QGLViewer moves its build output back to its source dir
find_library(QGLVIEWER_LIBRARIES
  NAMES qglviewer-qt4 qglviewer QGLViewer QGLViewer2 QGLViewer-qt5
  PATHS ${libQGLViewer_SOURCE_DIR}
  PATH_SUFFIXES QGLViewer QGLViewer/release)
target_link_libraries(libQGLViewer INTERFACE ${QGLVIEWER_LIBRARIES})
