cmake_minimum_required (VERSION 3.0)

include(ExternalProject)

message("Setting up zlib...")

set(ZLIB_URL "${CMAKE_CURRENT_LIST_DIR}/zlib-1.2.11.tar.gz")
set(ZLIB_DIR "${CMAKE_BINARY_DIR}/external_libs/zlib")

if(DEFINED EXTERNAL_INSTALL_DIR)
  set(ZLIB_INSTALL_DIR ${EXTERNAL_INSTALL_DIR})
  message("zlib: EXTERNAL_INSTALL_DIR is defined")
else()
  set(ZLIB_INSTALL_DIR "${ZLIB_DIR}/install")
endif() 

message("ZLIB_INSTALL_DIR: ${ZLIB_INSTALL_DIR}")

set(ZLIB_CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=${ZLIB_INSTALL_DIR})
set(ZLIB_CMAKE_ARGS ${ZLIB_CMAKE_ARGS} -DSKIP_INSTALL_FILES:BOOL=ON -DCMAKE_POSITION_INDEPENDENT_CODE=ON)
set(ZLIB_CMAKE_CACHE_ARGS "")
set(ZLIB_PATCH_COMMAND "")

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

if(WIN32)
  if(MINGW)
    set(ZLIB_LIBRARIES ${ZLIB_INSTALL_DIR}/lib/libzlib.a)
  else()
    set(ZLIB_LIBRARIES optimized ${ZLIB_INSTALL_DIR}/lib/zlibstatic.lib debug ${ZLIB_INSTALL_DIR}/lib/zlibstaticd.lib)
  endif()
else()
  set(ZLIB_LIBRARIES ${ZLIB_INSTALL_DIR}/lib/libz.a)
endif()

ExternalProject_Add(
  zlib-external
  URL ${ZLIB_URL}
  URL_MD5 1c9f62f0778697a09d36121ead88e08e
  DOWNLOAD_DIR ${ZLIB_DIR}/download
  SOURCE_DIR ${ZLIB_DIR}/source
  BINARY_DIR ${ZLIB_DIR}
  INSTALL_DIR ${ZLIB_INSTALL_DIR}
  CMAKE_ARGS "${ZLIB_CMAKE_ARGS}"
  CMAKE_CACHE_ARGS "${ZLIB_CMAKE_CACHE_ARGS}"
  BUILD_BYPRODUCTS ${ZLIB_LIBRARIES}
  UPDATE_COMMAND ""
  PATCH_COMMAND "${ZLIB_PATCH_COMMAND}"
)