#!/usr/bin/env bash

# See: http://wiki.qt.io/Building_Qt_5_from_Git
# See: http://doc.qt.io/qt-5/configure-options.html

REPO_URL='git://code.qt.io/qt/qt5.git'
REPO_FOLDER=qt5
QT_VERSION='5.10'

# ==============================================================================

RED='\e[1;31m'
BLUE='\e[1;34m'
NC='\e[0m'

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "${SCRIPT_DIR}/.."

# ==============================================================================

if [ ! -d "${REPO_FOLDER}/.git" ]; then
  git clone "${REPO_URL}" "${REPO_FOLDER}"
fi
cd "${REPO_FOLDER}"

while test $# -gt 0
do
  case "$1" in
    --clean)
      echo "Clean..."
      git submodule foreach 'git clean -dfx'
      ;;
    --*) echo "Invalid option: $1"
      ;;
  esac
  shift
done

git checkout "${QT_VERSION}"
if [[ $? != 0 ]] ; then
  printf "${RED}Unable to checkout ${QT_VERSION}.${NC}\n"
  exit 1
fi

./init-repository --module-subset=default,\
-qtandroidextras,\
-qtcharts,\
-qtdoc,\
-qtlocation,\
-qtmacextras,\
-qtnetworkauth,\
-qtpurchasing,\
-qtremoteobjects,\
-qtrepotools,\
-qtscript,\
-qtscxml,\
-qtsensors,\
-qtspeech,\
-qtwebchannel,\
-qtwebengine,\
-qtwebglplugin,\
-qtwebsockets,\
-qtwebview,\
-qtwinextras,\
-qtx11extras,\
-qtxmlpatterns \
-f

./configure -opensource -confirm-license -release -c++std c++11 -ccache -silent -nomake examples -nomake tests \
-prefix "/opt/qt-${QT_VERSION}" \
-qt-freetype \
-qt-harfbuzz \
-qt-libjpeg \
-qt-libpng \
-qt-pcre \
-qt-xcb \
-qt-xkbcommon \
-system-zlib

if [[ $? != 0 ]] ; then
  printf "${RED}Unknown configure option.${NC}\n"
  exit 1
fi

make -r -j5

printf "${NC}Please export configuration variables like this:${NC}\n"
printf "${BLUE}export PATH=\"/opt/qt-${QT_VERSION}/bin/:\$PATH\"${NC}\n"
printf "${BLUE}export Qt5_DIR=\"/opt/qt-${QT_VERSION}/lib/cmake/\"${NC}\n"
