#!/bin/bash -ex
#
# This script is run on travis for the install stage of mac builds.
#

#debug failed install
function debug() {
  cat ${CACHEDIR}/qt-${QT_VERSION}.env
  find ${CACHEDIR}/Qt -maxdepth 3 -ls
  cat ${CACHEDIR}/Qt/InstallationLog.txt
  cat ${CACHEDIR}/Qt/components.xml
  echo "$1" >&2
  exit 1
}

# validate install
function validate() {
  (
    set +e
    source ${CACHEDIR}/qt-${QT_VERSION}.env
    if [ "$(qmake -query QT_INSTALL_BINS)" != "${QTDIR}/bin" ]; then
      debug "ERROR: unexpected Qt location."
    fi
    if [ "$(qmake -query QT_VERSION)" != "${QT_VERSION}" ]; then
      debug "ERROR: wrong Qt version."
    fi
  )
}

QT_VERSION=${1:-5.12.2}
QT_VERSION_SHORT=${QT_VERSION//./}

# our expectation is that install-qt creates $QTDIR, $QTDIR/bin.
CACHEDIR=${HOME}/Cache
QTDIR=${CACHEDIR}/Qt/${QT_VERSION}/gcc_64

if [ -d "${QTDIR}/bin" ]; then
  echo "Using cached Qt."
  echo "If you need to clear the cache see"
  echo "https://docs.travis-ci.com/user/caching/#Fetching-and-storing-caches."
else
  rm -fr ${CACHEDIR}
  mkdir -p ${CACHEDIR}
  QT_CI_DOWNLOADER="wget -nv -c" PATH=${TRAVIS_BUILD_DIR}/tools/qtci:${PATH} install-qt-online "qt.qt5.${QT_VERSION_SHORT}.gcc_64" ${CACHEDIR}
  echo "export PATH=${QTDIR}/bin:$PATH" > ${CACHEDIR}/qt-${QT_VERSION}.env
  validate
fi
