cmake_minimum_required(VERSION 3.22) # FIXME: 3.24.2 / 3.25

project(pugixml-download NONE)

# Enable ExternalProject CMake module
include(ExternalProject)

option(ALLOW_DOWNLOADING_PUGIXML "If pugixml src tree is not found in location specified by PUGIXML_PATH, do fetch the archive from internet" OFF)
set(PUGIXML_PATH "/usr/src/pugixml" CACHE PATH "Path to the pugixml root tree.")

# Download and install pugixml

message(STATUS "Looking for pugixml sources")
message(STATUS "Looking for pugixml sources in ${PUGIXML_PATH}")
if(EXISTS "${PUGIXML_PATH}" AND IS_DIRECTORY "${PUGIXML_PATH}" AND EXISTS "${PUGIXML_PATH}/CMakeLists.txt")
  message(STATUS "Found pugixml in ${PUGIXML_PATH}")

  ExternalProject_Add(
    pugixml
    PREFIX            "${CMAKE_BINARY_DIR}"
    DOWNLOAD_DIR      "${CMAKE_BINARY_DIR}/download"
    SOURCE_DIR        "${PUGIXML_PATH}" # use existing src dir.
    BINARY_DIR        "${CMAKE_BINARY_DIR}/build"
    CONFIGURE_COMMAND ""
    BUILD_COMMAND     ""
    INSTALL_COMMAND   ""
    TEST_COMMAND      ""
  )
else()
  if(NOT ALLOW_DOWNLOADING_PUGIXML)
    message(SEND_ERROR "Did not find pugixml sources! Either pass correct path in PUGIXML_PATH, or enable ALLOW_DOWNLOADING_PUGIXML, or disable WITH_PUGIXML.")
  else()
    message(WARNING "Did not find pugixml sources! Fetching from web...")
    ExternalProject_Add(
      pugixml
      URL               https://github.com/zeux/pugixml/releases/download/v1.9/pugixml-1.9.tar.gz
      URL_HASH          SHA512=853a9d985aae537391c6524d5413ef4de237d99d96cc58ea7fe7152f786df1e408cdacd2e4387697e23c3e67cdc1d42b29de554501309eae16d86edd0e24785f
      PREFIX            "${CMAKE_BINARY_DIR}"
      STAMP_DIR         "${CMAKE_BINARY_DIR}/stamp"
      DOWNLOAD_DIR      "${CMAKE_BINARY_DIR}/download"
      SOURCE_DIR        "${CMAKE_BINARY_DIR}/src"
      BINARY_DIR        "${CMAKE_BINARY_DIR}/build"
      CONFIGURE_COMMAND ""
      BUILD_COMMAND     ""
      INSTALL_COMMAND   ""
      TEST_COMMAND      ""
    )
  endif()
endif()

ExternalProject_Get_Property(pugixml SOURCE_DIR BINARY_DIR)
file(WRITE pugixml-paths.cmake
"set(PUGIXML_SOURCE_DIR \"${SOURCE_DIR}\")
set(PUGIXML_BINARY_DIR \"${BINARY_DIR}\")
")
