cmake_minimum_required(VERSION 3.22) # FIXME: 3.24.2 / 3.25

project(zlib-download NONE)

# Enable ExternalProject CMake module
include(ExternalProject)

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

# Download and install ZLIB

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

  ExternalProject_Add(
    zlib
    PREFIX            "${CMAKE_BINARY_DIR}"
    DOWNLOAD_DIR      "${CMAKE_BINARY_DIR}/download"
    SOURCE_DIR        "${ZLIB_PATH}" # use existing src dir.
    BINARY_DIR        "${CMAKE_BINARY_DIR}/build"
    CONFIGURE_COMMAND ""
    BUILD_COMMAND     ""
    INSTALL_COMMAND   ""
    TEST_COMMAND      ""
  )
else()
  if(NOT ALLOW_DOWNLOADING_ZLIB)
    message(SEND_ERROR "Did not find ZLIB sources! Either pass correct path in ZLIB_PATH, or enable ALLOW_DOWNLOADING_ZLIB, or disable USE_BUNDLED_ZLIB or disable WITH_ZLIB.")
  else()
    message(WARNING "Did not find ZLIB sources! Fetching from web...")
    ExternalProject_Add(
      zlib
      URL               https://downloads.sourceforge.net/project/libpng/zlib/1.2.11/zlib-1.2.11.tar.xz
      URL_HASH          SHA512=b7f50ada138c7f93eb7eb1631efccd1d9f03a5e77b6c13c8b757017b2d462e19d2d3e01c50fad60a4ae1bc86d431f6f94c72c11ff410c25121e571953017cb67
      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(zlib SOURCE_DIR BINARY_DIR)
file(WRITE zlib-paths.cmake
"set(ZLIB_SOURCE_DIR \"${SOURCE_DIR}\")
set(ZLIB_BINARY_DIR \"${BINARY_DIR}\")
")
