#!/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."
  if [ "${TRAVIS_EVENT_TYPE}" = "cron" ]; then
    # the cache is being used.  modify it to reset expiration date.
    date > ${CACHEDIR}/timestamp
  fi
  if [ -f "${CACHEDIR}/timestamp" ]; then
    echo -n "Cache timestamp: "
    cat "${CACHEDIR}/timestamp"
  fi
else
  rm -fr ${CACHEDIR}
  mkdir -p ${CACHEDIR}
  pushd ${CACHEDIR}
  # install-qt creates the install at $PWD/Qt.
  QT_CI_PACKAGES=qt.qt5.${QT_VERSION_SHORT}.gcc_64,qt.qt5.${QT_VERSION_SHORT}.qtwebengine QT_CI_DOWNLOADER="wget -nv -c" PATH=${TRAVIS_BUILD_DIR}/tools/qtci:${PATH} install-qt ${QT_VERSION}
  popd
  validate
  rm ${CACHEDIR}/qt-opensource*.run
fi

# prepare locale for test_encoding_latin1, requires locales package.
sudo rm -rf /var/lib/apt/lists/* \
  && sudo sed -i 's/^# *\(en_US ISO-8859-1\)/\1/' /etc/locale.gen \
  && sudo locale-gen \
  && locale -a
