#!/bin/bash -e
# Reference:
#   https://github.com/musescore/MuseScore/blob/master/build/travis/job_macos/install.sh

QT_VERSION=${1:-5.12.0}
QT_TARGET_CATALOG=${2:-$PWD}
QT_CI_DOWNLOADER=${QT_CI_DOWNLOADER:-"wget -c -N"}

QT_MAJOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 1)
QT_MINOR_VERSION=$(echo ${QT_VERSION} | cut -d "." -f 2)
if [ "$(uname)" = "Darwin" ]; then
  if { [ "${QT_MAJOR_VERSION}" -eq 5 ] && [ "${QT_MINOR_VERSION}" -ge 9 ]; } || [ "${QT_MAJOR_VERSION}" -ge 6 ]; then
    # this was good from 5.9.0 through at least 5.12.0
    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-${QT_VERSION}.dmg
  else
    # this was good from 5.2.1 through 5.8.0
    DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-mac-x64-clang-${QT_VERSION}.dmg
  fi
  COMPILER=clang_64
elif [ "$(uname)" = "Linux" ]; then
  # this was good from 5.2.1 through at least 5.12.0
  DOWNLOAD_URL=https://download.qt.io/archive/qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${QT_VERSION}/qt-opensource-linux-x64-${QT_VERSION}.run
  COMPILER=gcc_64
else
  echo "Unsupported system." >&2
  exit 1
fi
INSTALLER=$(basename $DOWNLOAD_URL)
ENVFILE=${QT_TARGET_CATALOG}/qt-${QT_VERSION}.env

echo Downloading Qt
${QT_CI_DOWNLOADER} ${DOWNLOAD_URL} || exit 1

echo Installing Qt
if [ "$(uname)" = "Darwin" ]; then
  INSTALLER_NAME=${INSTALLER%.*}
  APPFILE=/Volumes/${INSTALLER_NAME}/${INSTALLER_NAME}.app/Contents/MacOS/${INSTALLER_NAME}
  hdiutil attach ${PWD}/${INSTALLER}
  sandbox-exec -n no-network extract-qt-installer $APPFILE ${QT_TARGET_CATALOG}/Qt
  # workaround apparent exit of extract-qt-installer before finished,
  # which results in hdiutil "hdiutil: couldn't unmount "disk1" - Resource busy"
  # and the install resources not being available.
  #hdiutil detach /Volumes/${INSTALLER_NAME}
  count=0
  until hdiutil detach /Volumes/${INSTALLER_NAME} || [ $count -ge 12 ]
  do
    echo "Wait and attempt to detach again"
    count=`expr $count + 1`
    sleep 5
  done
elif [ "$(uname)" = "Linux" ]; then
  unshare -r -n extract-qt-installer ${PWD}/${INSTALLER} ${QT_TARGET_CATALOG}/Qt
fi

echo Create ${ENVFILE}
if [ -d "${QT_TARGET_CATALOG}/Qt/${QT_VERSION}/${COMPILER}/bin" ]; then
  echo "export PATH=${QT_TARGET_CATALOG}/Qt/${QT_VERSION}/${COMPILER}/bin:$PATH" > ${ENVFILE}
elif [ -d "${QT_TARGET_CATALOG}/Qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${COMPILER}/bin" ]; then
  # some packages use an abbreviated version x.y in the path instead of x.y.z
  echo "export PATH=${QT_TARGET_CATALOG}/Qt/${QT_MAJOR_VERSION}.${QT_MINOR_VERSION}/${COMPILER}/bin:$PATH" > ${ENVFILE}
fi

