# This script drives download of prebuilt packages during the build.
# The top-level CMakeLists.txt configures packages and tool locations.
set(packages "@PREBUILT_PACKAGES@")
set(python "@PYTHON_EXECUTABLE@")
set(install_dir "@CMAKE_SOURCE_DIR@/..")
set(scp "@SCP_EXECUTABLE@")
set(scripts_dir "@SCRIPTS_DIR@")
set(sentinel_dir "@CMAKE_BINARY_DIR@/prepare")
set(prebuilt_type "@PREBUILT_TYPE@")

# In proprietary mode we use scp for download.
set(proprietary "@INSTALL_PROPRIETARY@")
if(proprietary)
  set(scp_option "--scp=${scp}")
  set(proprietary_message " proprietary")
endif(proprietary)

foreach(package ${packages})
  if(${install_dir}/install.xml IS_NEWER_THAN ${sentinel_dir}/${package}_installed)
    # This package is missing or out of date.
    message(STATUS "Obtaining${proprietary_message} prebuilt '${package}'")
    execute_process(
      COMMAND ${python} install.py -p${prebuilt_type} --install-dir=${install_dir} ${scp_option} ${package}
      WORKING_DIRECTORY ${scripts_dir}
      RESULT_VARIABLE result
      )
    if(result STREQUAL 0)
      # Write a sentinel to avoid attempting a download again.
      file(WRITE ${sentinel_dir}/${package}_installed "Obtained '${package}'")
    else(result STREQUAL 0)
      # Remove the sentinel to ensure a download is attempted again.
      file(REMOVE ${sentinel_dir}/prebuilt
                  ${sentinel_dir}/${package}_installed)
      message(FATAL_ERROR
        "Failed to download or unpack prebuilt '${package}'.  "
        "Process returned: ${result}")
    endif(result STREQUAL 0)
  else(${install_dir}/install.xml IS_NEWER_THAN ${sentinel_dir}/${package}_installed)
    # This package is ready.
    message(STATUS "Prebuilt '${package}' is up-to-date")
  endif(${install_dir}/install.xml IS_NEWER_THAN ${sentinel_dir}/${package}_installed)
endforeach(package)

# Store a sentinel to avoid running this script unnecessarily.
file(WRITE ${sentinel_dir}/prebuilt "All prebuilts obtained successfully\n")
