include_guard(GLOBAL)

if(NOT DEFINED PIP_VERSION)
  set(PIP_VERSION "20.2.3")
endif()

if(NOT DEFINED PIP_PACKAGES_PATH)
  set(PIP_PACKAGES_PATH "${CMAKE_BINARY_DIR}/python" CACHE PATH "Path to install the pip packages.")
endif()

find_package(Python3 COMPONENTS Interpreter QUIET)

if(Python3_FOUND)
  find_package(pip ${PIP_VERSION} QUIET)
  if(PIP_FOUND)
    message(NOTE "Found pip : ${PIP_EXECUTABLE} (found version \"${PIP_VERSION}\")")
  else()
    set(PIP_URL "https://bootstrap.pypa.io/get-pip.py")
    set(PYTHONPATH "${CMAKE_BINARY_DIR}/python")
    message(NOTE "Installing pip ${PIP_VERSION}")
    if(NOT EXISTS "${CMAKE_BINARY_DIR}/get-pip.py")
      file(DOWNLOAD "${PIP_URL}" "${CMAKE_BINARY_DIR}/get-pip.py" SHOW_PROGRESS)
    endif()
    if(NOT EXISTS "${CMAKE_BINARY_DIR}/python")
      file(MAKE_DIRECTORY "${CMAKE_BINARY_DIR}/python")
    endif()
    execute_process(COMMAND ${Python3_EXECUTABLE} "${CMAKE_BINARY_DIR}/get-pip.py" "-t" "${PIP_PACKAGES_PATH}")
    find_package(pip ${PIP_VERSION} REQUIRED)
    if(PIP_FOUND)
      message(NOTE "Found pip : ${PIP_EXECUTABLE} (found version \"${PIP_VERSION}\")")
    endif()
  endif()
else()
  message(WARN "Python3 not found. Cannot install pip")
endif()

