# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Massimo Callegari <support@qlcplus.org>
# Maintainer: Tim S <stahta01@gmail.com>

#_variant=-static
_variant=-shared

# The Qt5 GIT repository to clone from
_qt_git_repo=https://code.qt.io/qt

# Branch tested for applying patches include 5.6 and 5.9.
# The Qt5 GIT branch to clone and build (replace with 'dev' to build the bleeding edge sources)
_qt_git_branch=5.9    # When changing this value the x86_64 and i686 folders
#                     # under the src folder must be deleted to have a good build.

# "./configure" is more likely to have windows build issues.
#_configure=./configure.bat
# configure.bat fails for Version 5.7.
_configure=./configure

# The way Qt5 libraries are built. Possible values are '-release', '-debug' or '-debug-and-release'
_build_mode=-release
# _build_mode=-debug
# _build_mode=-debug-and-release

# Tune the following to decide how and what to build
_with_icu=yes
_with_fontconfig=yes
_with_openssl=yes
_with_dbus=yes
_system_freetype=yes
_system_zlib=yes
_system_pcre2=yes
_system_libpng=yes
_system_libjpeg=yes
_system_harfbuzz=yes
_make_docs=no
_build_examples=no
_build_script=no
_build_tools=no
_build_tests=no
_build_multimedia=no
_build_imageformats=no
_build_xmlpatterns=no
_build_declarative=no
_build_datavis3d=no
_build_activeqt=no
_build_serialport=no
_build_svg=no
_build_connectivity=no
_build_location=no
_build_charts=no
_build_sensors=no
_build_websockets=no
_build_gamepad=no
_build_webchannel=no
_build_winextras=no

# Getting crashes that only happen in release builds?
# Define this and you may have a hope of figuring out
# why ..
_debuggable_release=no
#_debuggable_release=yes

if [ "${_variant}" = "-static" ]; then
  _namesuff="-static"
  _system_freetype=no
#  _ltcg="yes"
  _ltcg="no"
else
  _namesuff=
  _ltcg="no"
fi

_basename=qt5
_realname=${_basename}${_namesuff}
pkgbase=mingw-w64-${_basename}-git
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}-git"
pkgver=5.9.2.r926.6c4eb77
pkgrel=1
arch=('any')
url='https://www.qt.io/'
install=qt5.install
license=('GPL3' 'LGPL' 'FDL' 'custom')
provides=(
  "${MINGW_PACKAGE_PREFIX}-${_realname}"
  "${MINGW_PACKAGE_PREFIX}-qt5-base${_namesuff}"
)
conflicts=("${MINGW_PACKAGE_PREFIX}-${_realname}")

depends=(
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
  "${MINGW_PACKAGE_PREFIX}-qtbinpatcher"
   $([[ "$_variant" == "-shared" ]] && echo "${MINGW_PACKAGE_PREFIX}-assimp")
   $([[ "$_with_dbus" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-dbus")
   $([[ "$_with_fontconfig" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-fontconfig")
   $([[ "$_system_freetype" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-freetype")
   $([[ "$_system_harfbuzz" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-harfbuzz")
   "${MINGW_PACKAGE_PREFIX}-jasper"
   $([[ "$_system_libjpeg" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-libjpeg")
   "${MINGW_PACKAGE_PREFIX}-libmng"
   $([[ "$_system_libpng" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-libpng")
   "${MINGW_PACKAGE_PREFIX}-libtiff"
   "${MINGW_PACKAGE_PREFIX}-libxml2"
   "${MINGW_PACKAGE_PREFIX}-libxslt"
   "${MINGW_PACKAGE_PREFIX}-libwebp"
   $([[ "$_with_openssl" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-openssl")
   $([[ "$_system_pcre2" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-pcre2")
   "${MINGW_PACKAGE_PREFIX}-sqlite3"
   "${MINGW_PACKAGE_PREFIX}-xpm-nox"
   $([[ "$_system_zlib" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-zlib")
   $([[ "$_with_icu" == "yes" ]] && echo \
      "${MINGW_PACKAGE_PREFIX}-icu" \
      "${MINGW_PACKAGE_PREFIX}-icu-debug-libs" )
)
optdepends=(
  $([[ "$_variant" == "-shared" ]] && echo \
    "${MINGW_PACKAGE_PREFIX}-libmariadbclient" \
    "${MINGW_PACKAGE_PREFIX}-firebird" \
    "${MINGW_PACKAGE_PREFIX}-postgresql")
)
makedepends=(
  "git"
  "diffutils"
  "gperf"
  "m4"
  "make"
  "patch"
  "perl"
  "dos2unix"
  "${MINGW_PACKAGE_PREFIX}-ruby"
  "${MINGW_PACKAGE_PREFIX}-gcc"
  "${MINGW_PACKAGE_PREFIX}-pkg-config"
  "${MINGW_PACKAGE_PREFIX}-python2"
  "${MINGW_PACKAGE_PREFIX}-make"
  $([[ "$_variant" == "-static" ]] && echo \
    "${MINGW_PACKAGE_PREFIX}-dbus" \
    "${MINGW_PACKAGE_PREFIX}-openssl")
  $([[ "$_variant" == "-shared" ]] && echo \
    "${MINGW_PACKAGE_PREFIX}-libmariadbclient" \
    "${MINGW_PACKAGE_PREFIX}-firebird2" \
    "${MINGW_PACKAGE_PREFIX}-postgresql")
)

groups=("${MINGW_PACKAGE_PREFIX}-qt" "${MINGW_PACKAGE_PREFIX}-qt5")
options=('!strip' 'staticlibs')

source=(
  0001-qt-5.6-oracle-driver-prompt.patch
  0001-qt-5.8.0-fix-sql-libraries-mingw.patch
  0001-qt-5.9.1-fix-sql-libraries-mingw.patch
  0002-qt-5.6-use-fbclient-instead-of-gds32.patch
  0002-qt-5.8.1-configure-gcc-before-clang.patch
  0003-qt-5.6-use-mingw-built-mysql-library.patch
  0003-qt-5.8.0-autodetect-fontconfig.patch
  0005-qt-5.3.0-syncqt-fix.patch
  0006-qt-5.3.0-win_flex-replace.patch
  0007-qt-5.3.0-win32-g-Enable-static-builds.patch
  0007-qt-5.9.0-win32-g-Enable-static-builds.patch
  0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
  0011-qt-5.6-win32-g++-allow-static-dbus-1.patch
  0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch
  0012-qt-5.6-compileTest-for-icu-after-setting-static-or-shared.patch
  0014-qt-5.6-fix-configure-tests.patch
  0015-qt-5.6-properly-split-libraries-mingw.patch
  0016-qt-5.6-win32-g++-use-qpa-genericunixfontdatabase.patch
  0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch
  0017-qt-5.3.0-fix-examples-building.patch
  0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
  0024-qt-5.9.2-icu-add-U_LIB_SUFFIX_C_NAME.patch
  0025-qt-5.6-force-using-make-on-msys.patch
  0025-qt-5.8.0-force-using-make-on-msys.patch
  0030-qt-5.3.1-workaround-ansidecl-h-PTR-define-conflict.patch
  0031-qt-5.5.0-workaround-BOOL-define-conflict.patch
  0034-qt-5.3.2-Use-QMAKE_PREFIX_STATICLIB-in-create_cmake-prf.patch
  0035-qt-5.3.2-dont-add-resource-files-to-qmake-libs.patch
  0036-qt-5.3.2-win32-qt5-static-cmake-link-ws2_32-and--static.patch
  0037-qt-5.4.0-Improve-cmake-plugin-detection-as-not-all-are-suffixed-Plugin.patch
  0038-qt-5.5.0-cmake-Rearrange-STATIC-vs-INTERFACE-targets.patch
  0039-qt-5.4.0-Make-it-possible-to-use-static-builds-of-Qt-with-CMa.patch
  0040-qt-5.4.0-Generate-separated-libraries-in-prl-files-for-CMake.patch
  0041-qt-5.4.0-Fix-mingw-create_cmake-prl-file-has-no-lib-prefix.patch
  0042-qt-5.4.0-static-cmake-also-link-plugins-and-plugin-deps.patch
  0043-qt-5.5.0-static-cmake-regex-QT_INSTALL_LIBS-in-QMAKE_PRL_LIBS_FOR_CMAKE.patch
  0045-qt-5.4.1-static-use-qminimal-platform-plugin-for-qcollectiongenerator.patch
  0046-qt-5.6-Revert-Revert-fix-NTFS-mount-points.patch
  0048-qt-5.4.2-win32-Avoid-platformNativeInterface-segfaults-with-minimal-platform.patch
  0049-qt-5.8.0-win32-do-not-use-fontconfig.patch
  0049-qt-5.9.0-win32-do-not-use-fontconfig.patch
  0051-qt-5.9.0-disable-qtlocation-mapboxgl-plugin.patch
  0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch
  0125-qt-5.8.0-windeployqt-fixes.patch
  0125-qt-5.9.0-windeployqt-fixes.patch
  0300-qt-5.8.0-cast-errors.patch
)

# qt5-static must be kept in its own prefix hierarchy
# as otherwise it will conflict with qt5 itself
if [ "${_variant}" = "-static" ]; then
  _qt5_prefix="${MINGW_PREFIX}/${_realname}"
else
  _qt5_prefix="${MINGW_PREFIX}"
fi


# Thiago's patch doesn't contain the configure script changes
# needed, you may be able to get somewhere with this in the
# meantime (probably not though!)
if [ "${_ltcg}" = "yes" ]; then
   LTCG_CFLAGS="-flto-partition=1to1 -flto -ffat-lto-objects"
   LTCG_LFLAGS="-flto-partition=1to1 -flto -ffat-lto-objects"
fi

pkgver() {
  cd "${_startdir}/${_basename}"

  local full_version=${_qt_version}.r$(git rev-list --count --first-parent HEAD ).$(git rev-parse --short HEAD )

  printf "%s" $full_version
}

# Translates using cygpath according to the ${_make} being used
# (so either mingw32-make or MSYS2 make can be used)
path_conv_for_make() {
#  if [ "${_make}" = "mingw32-make" ]; then
#    echo -n "${1}" | sed "s|${MINGW_PREFIX}|$(cygpath -m ${MINGW_PREFIX})|g"
#  else # MSYS2 make
    MINGW_PREFIX_W=$(cygpath -m ${MINGW_PREFIX})
    echo -n "${1}" | sed "s|${MINGW_PREFIX_W}|$(cygpath -u ${MINGW_PREFIX})|g"
#  fi
}

# Runs pkg-config with all arguments, then calls path_conv_for_make on each
# result and then adds delimiter between -I/-L/-l and path - both configure
# and configure.bat prefer this. Results returned as an array.
pkg_config_qt5() {
  local _res=$(pkg-config $*)
  local -a _final=()
  for _part in $(path_conv_for_make "${_res}"); do
      _final+=($(echo -n "${_part}" | sed "s|-\([ILl]\)\(.*\)|-\1|g"))
      _final+=($(echo -n "${_part}" | sed "s|-\([ILl]\)\(.*\)|\2|g"))
  done
  echo "${_final[@]}"
}

git_switch_to_branch () {
    local current_branch=$(git rev-parse --abbrev-ref HEAD)
    if [[ $current_branch != $1 ]]; then
      git reset --hard
      echo "git checkout $1 || git checkout -b $1 --track origin/$1"
      git checkout $1 || git checkout -b $1 --track origin/$1
    fi
}

git_clone_or_switch_to_branch () {
  if [ ! -f $1/.cloned ]; then
    echo "git clone --no-single-branch --no-checkout --branch "$_qt_git_branch" "$_qt_git_repo"/$1.git"
    git clone --no-single-branch --no-checkout --branch "$_qt_git_branch" "$_qt_git_repo"/$1.git
    touch $1/.cloned
  else
    pushd $1 > /dev/null
      git_switch_to_branch $_qt_git_branch
    popd > /dev/null
  fi
}

git_clone_or_update_local_submodule () {
  if [ ! -f $1/.cloned ]; then
    echo "git clone --branch "$_qt_git_branch" --quiet "${_startdir}"/${_basename}/$1 $1"
    git clone --branch "$_qt_git_branch" --quiet "${_startdir}"/${_basename}/$1 $1
    touch $1/.cloned
  else
    echo "$1 already cloned."
    pushd $1 > /dev/null
      if [[ $1 == "qtbase" || \
            $1 == "qtactiveqt"  || \
            $1 == "qtcanvas3d"  || \
            $1 == "qtdeclarative" || \
            $1 == "qtimageformats"  || \
            $1 == "qtlocation"  || \
            $1 == "qtsensors" || \
            $1 == "qttools" ]] ; then
        echo "Resetting $1 ..."
        git reset --hard HEAD
      fi
      git_switch_to_branch $_qt_git_branch
      echo "Pulling $1 ..."
      git pull
    popd > /dev/null
  fi
}

prepare_build_folder() {
  # MSYS2 gperf cannot handle \r\n.
  find . -name "*.gperf" -exec dos2unix "{}" \;

  if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
    patch -p1 -i ${srcdir}/0001-qt-5.6-oracle-driver-prompt.patch
    patch -p1 -i ${srcdir}/0002-qt-5.6-use-fbclient-instead-of-gds32.patch
    patch -p1 -i ${srcdir}/0003-qt-5.6-use-mingw-built-mysql-library.patch
  else
    if [[ ${_qt_version:0:3} != "5.7" ]] ; then
      if [[ ${_qt_version:0:3} == "5.8" || ${_qt_version} == "5.9.0" ]] ; then
        patch -p1 -i ${srcdir}/0001-qt-5.8.0-fix-sql-libraries-mingw.patch
      else
        patch -p1 -i ${srcdir}/0001-qt-5.9.1-fix-sql-libraries-mingw.patch
      fi
    fi
  fi
  if [[ ${_qt_version:0:3} != "5.6" && ${_qt_version:0:3} != "5.7" ]] ; then
    patch -p1 -i ${srcdir}/0002-qt-5.8.1-configure-gcc-before-clang.patch
    patch -p1 -i ${srcdir}/0003-qt-5.8.0-autodetect-fontconfig.patch
  fi
  patch -p1 -i ${srcdir}/0005-qt-5.3.0-syncqt-fix.patch
  patch -p1 -i ${srcdir}/0006-qt-5.3.0-win_flex-replace.patch

  # Some patches are against qtbase's repository.
  pushd qtbase > /dev/null
    if [[ ${_qt_version:0:3} == "5.9" ]] ; then
      patch -p1 -i ${srcdir}/0007-qt-5.9.0-win32-g-Enable-static-builds.patch
    else
      if [[ ${_qt_version:0:4} != "5.10" ]] ; then
        patch -p1 -i ${srcdir}/0007-qt-5.3.0-win32-g-Enable-static-builds.patch
      fi
    fi
    patch -p1 -i ${srcdir}/0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
    if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
      patch -p1 -i ${srcdir}/0011-qt-5.6-win32-g++-allow-static-dbus-1.patch
    else
      popd > /dev/null
        patch -p1 -i ${srcdir}/0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch
      pushd qtbase > /dev/null
    fi

    # The next patch needs some work. It's moving a block of shell script un-necessarily
    # as the bit: QMAKE_CONFIG="$QMAKE_CONFIG static" before calling compileTest is what
    # actually made it work. There may be a good reason for not adding static to QMAKE_CONFIG
    # so it might be necessary to back up the value, do compileTest then restore it after.
    if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
      patch -p1 -i ${srcdir}/0012-qt-5.6-compileTest-for-icu-after-setting-static-or-shared.patch
    fi
  popd > /dev/null

  if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
    patch -p1 -i ${srcdir}/0014-qt-5.6-fix-configure-tests.patch
    patch -p1 -i ${srcdir}/0015-qt-5.6-properly-split-libraries-mingw.patch
    patch -p1 -i ${srcdir}/0016-qt-5.6-win32-g++-use-qpa-genericunixfontdatabase.patch
  else
    patch -p1 -i ${srcdir}/0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch
  fi
  if [[ ${_qt_version:0:3} != "5.9" ]] ; then
    patch -p1 -i ${srcdir}/0017-qt-5.3.0-fix-examples-building.patch
  fi

  if [[ ${_qt_version} != "5.9.2" ]] ; then
    patch -p1 -i ${srcdir}/0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
  else
    patch -p1 -i ${srcdir}/0024-qt-5.9.2-icu-add-U_LIB_SUFFIX_C_NAME.patch
  fi
  if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
    patch -p1 -i ${srcdir}/0025-qt-5.6-force-using-make-on-msys.patch
  else
    patch -p1 -i ${srcdir}/0025-qt-5.8.0-force-using-make-on-msys.patch
  fi

  pushd qtbase > /dev/null
    patch -p1 -i ${srcdir}/0030-qt-5.3.1-workaround-ansidecl-h-PTR-define-conflict.patch
  popd > /dev/null

  patch -p1 -i ${srcdir}/0031-qt-5.5.0-workaround-BOOL-define-conflict.patch

  # See discussion at https://bugreports.qt.io/browse/QTBUG-41292
  # I think what is possibly happening instead is that the Debug and Release
  # builds are happening in parallel and this causes the error. While Ossi's
  # suggestion (below) doesn't fix the problem entirely, it makes the chances
  # of it happening near 0.  His take on it is that we should have different
  # target files for RegExpJitTables.h for each of release and debug.
  patch -p1 -i ${srcdir}/0034-qt-5.3.2-Use-QMAKE_PREFIX_STATICLIB-in-create_cmake-prf.patch
  patch -p1 -i ${srcdir}/0035-qt-5.3.2-dont-add-resource-files-to-qmake-libs.patch

  # Patches so that qt5-static can be used with cmake.
  patch -p1 -i ${srcdir}/0036-qt-5.3.2-win32-qt5-static-cmake-link-ws2_32-and--static.patch
  patch -p1 -i ${srcdir}/0037-qt-5.4.0-Improve-cmake-plugin-detection-as-not-all-are-suffixed-Plugin.patch

  pushd qtbase > /dev/null
    patch -p1 -i ${srcdir}/0038-qt-5.5.0-cmake-Rearrange-STATIC-vs-INTERFACE-targets.patch
  popd > /dev/null

  patch -p1 -i ${srcdir}/0039-qt-5.4.0-Make-it-possible-to-use-static-builds-of-Qt-with-CMa.patch
  patch -p1 -i ${srcdir}/0040-qt-5.4.0-Generate-separated-libraries-in-prl-files-for-CMake.patch
  patch -p1 -i ${srcdir}/0041-qt-5.4.0-Fix-mingw-create_cmake-prl-file-has-no-lib-prefix.patch
  patch -p1 -i ${srcdir}/0042-qt-5.4.0-static-cmake-also-link-plugins-and-plugin-deps.patch
  patch -p1 -i ${srcdir}/0043-qt-5.5.0-static-cmake-regex-QT_INSTALL_LIBS-in-QMAKE_PRL_LIBS_FOR_CMAKE.patch

  # More odds and sods.
  patch -p1 -i ${srcdir}/0045-qt-5.4.1-static-use-qminimal-platform-plugin-for-qcollectiongenerator.patch

  pushd qtbase > /dev/null
    if [[ ${_qt_version:0:3} == "5.6" || ${_qt_version:0:3} == "5.7" ]] ; then
      patch -p1 -i ${srcdir}/0046-qt-5.6-Revert-Revert-fix-NTFS-mount-points.patch
    fi
  popd > /dev/null

  rm -f ./qtbase/src/gui/opengl/qopengles2ext.h

  patch -p1 -i ${srcdir}/0048-qt-5.4.2-win32-Avoid-platformNativeInterface-segfaults-with-minimal-platform.patch

  if [[ ${_qt_version:0:3} == "5.8" ]] ; then
    patch -p1 -i ${srcdir}/0049-qt-5.8.0-windows-not-use-fontconfig.patch
  else
    if [[ ${_qt_version:0:3} == "5.9" ]] ; then
      patch -p1 -i ${srcdir}/0049-qt-5.9.0-win32-do-not-use-fontconfig.patch
    fi
  fi

  if [[ ${_qt_version:0:3} == "5.9" ]] ; then
    if [[ ${_qt_version} == "5.9.0" ]] ; then
      patch -p1 -i ${srcdir}/0051-qt-5.9.0-disable-qtlocation-mapboxgl-plugin.patch
    else
      if [[ ${_qt_version} == "5.9.1" ]] ; then
        patch -p1 -i ${srcdir}/0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch
      fi
    fi
  fi

  pushd qttools > /dev/null
    if [[ ${_qt_version:0:3} == "5.8" ]] ; then
      patch -p1 -i ${srcdir}/0125-qt-5.8.0-windeployqt-fixes.patch
    else
      if [[ ${_qt_version:0:3} == "5.9" ]] ; then
        patch -p1 -i ${srcdir}/0125-qt-5.9.0-windeployqt-fixes.patch
      fi
    fi
  popd > /dev/null

  if [[ ${_qt_version:0:3} == "5.8" ]] ; then
    patch -p1 -i ${srcdir}/0300-qt-5.8.0-cast-errors.patch
  fi

  local _ARCH_TUNE=
  case ${MINGW_CHOST} in
    i686*)
      _ARCH_TUNE="-march=i686 -mtune=core2"
    ;;
    x86_64*)
      _ARCH_TUNE="-march=nocona -mtune=core2"
    ;;
  esac

  # Determine the CFLAGS, DEBUG_CFLAGS and LDFLAGS that we will tell qmake.conf about.
  # If this is qt5-static, we'd like to add -Os in an attempt to reduce size a little,
  # however there's an ICE in GCC 4.9.1 with x86_64, so must tread carefully.
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61207
  # Unlike OPTIM_D, please keep this one down here since it is not user selectable due
  # to the GCC bug.
  # This is the default, prevent re-appending.
  # OPTIM_O="-O2"
  if [ "${_variant}" = "-static" -a "${CARCH}" = "i686" ]; then
    OPTIM_O="-Os"
  fi

  if [ "${_debuggable_release}" = "yes" ]; then
    QMAKE_LFLAGS_RELEASE=
    OPTIM_O="${OPTIM_O} -g"
  else
    QMAKE_LFLAGS_RELEASE="-Wl,-s,--relax,--gc-sections"
    OPTIM_O="${OPTIM_O} -ffunction-sections -fdata-sections"
  fi

  BIGOBJ_FLAGS="-Wa,-mbig-obj"

  # Append these ones ..
  sed -i "s|^QMAKE_CFLAGS .*= \(.*\)$|QMAKE_CFLAGS            = \1 ${_ARCH_TUNE} ${BIGOBJ_FLAGS} ${LTCG_CFLAGS}|g" qtbase/mkspecs/win32-g++/qmake.conf
  if [ -n "$OPTIM_D" ]; then
    sed -i "s|^QMAKE_CFLAGS_DEBUG .*= \(.*\)$|QMAKE_CFLAGS_DEBUG      = \1 ${OPTIM_D}|g" qtbase/mkspecs/win32-g++/qmake.conf
  fi
  if [ -n "$OPTIM_O" ]; then
    sed -i "s|^QMAKE_CFLAGS_RELEASE .*= \(.*\)$|QMAKE_CFLAGS_RELEASE    = \1 ${OPTIM_O}|g" qtbase/mkspecs/win32-g++/qmake.conf
  fi
  sed -i "s|^QMAKE_LFLAGS            =\(.*\)$|QMAKE_LFLAGS            = \1 ${LTCG_LFLAGS}|g" qtbase/mkspecs/win32-g++/qmake.conf
  # But overwrite this one.
  sed -i "s|^QMAKE_LFLAGS_RELEASE .*= \(.*\)$|QMAKE_LFLAGS_RELEASE    = ${QMAKE_LFLAGS_RELEASE}|g" qtbase/mkspecs/win32-g++/qmake.conf
}

_qt_modules=(
  qtmultimedia
  qtconnectivity
  qtdeclarative
  qtdoc
  qttools
  qttranslations
  qtwebsockets
)
# Qt Add-On modules
_qt_modules+=(
  qt3d
  qtactiveqt
# qtandroidextras           # Is this useful on Windows?
  qtcanvas3d
  qtcharts
  qtdatavis3d
  qtgraphicaleffects
  qtimageformats
  qtlocation
# qtmacextras               # Is this useful on Windows?
  qtpurchasing
  qtquickcontrols
  qtquickcontrols2
  qtscript                  # Deprecated in 5.9
  qtsensors
  qtserialbus
  qtserialport
  qtsvg
  qtvirtualkeyboard
  qtwebchannel
  qtwinextras
# qtx11extras               # Is this useful on Windows?
  qtxmlpatterns
)
if [[ ${_qt_git_branch:0:3} == "5.6" ]] ; then
  _qt_modules+=(qtenginio)   # Lasted updated in 5.6.0
else
  _qt_modules+=(qtgamepad)   # Added in 5.7
  _qt_modules+=(qtscxml)     # Added in 5.7
fi

prepare() {
  cd ..                 # Change to the folder above ${srcdir}
  _startdir=$(pwd)      # Should be folder that contains PKGBUILD file.

  cd "${_startdir}"

  ### Check out the git source code
  #
  # Check out the git super module source code
  git_clone_or_switch_to_branch ${_basename}

  cd ${_basename}
  git_clone_or_switch_to_branch "qtbase"

  pushd qtbase > /dev/null
    git checkout HEAD -- ".qmake.conf"
  popd > /dev/null

  _qt_version=$(head -n 34 qtbase/.qmake.conf | grep 'MODULE_VERSION' | sed -e 's/.* //' | tr '\n' '.' | sed 's/.$/\n/')
  echo "_qt_version := ${_qt_version}"

  # Check out the git submodule source code
  for submodule in ${_qt_modules[@]}; do
    git_clone_or_switch_to_branch ${submodule}
  done
}

build() {
  cd "${srcdir}"

  if [ ! -d ${CARCH}/.git ]; then
    git clone  --branch "$_qt_git_branch" --quiet --local "${_startdir}"/${_basename} ${CARCH}
  fi

  cd ${CARCH}
    git pull

    git_clone_or_update_local_submodule qtbase

    for submodule in ${_qt_modules[@]}; do
      git_clone_or_update_local_submodule ${submodule}
    done

  cd "${srcdir}"/${CARCH}

  prepare_build_folder

  local _buildpkgdir=${pkgdirbase}/${pkgname}/${_qt5_prefix}
  mkdir -p ${_buildpkgdir}
  local QTDIR_WIN=$(cygpath -am ${_buildpkgdir})

  local _freetype2_pkgconf=""
  if [[ "$_system_freetype" == "yes" ]]; then
    _freetype2_pkgconf="freetype2"
  fi

  local -a _extra_incpaths=($(pkg_config_qt5 --cflags-only-I dbus-1 libxml-2.0 ${_freetype2_pkgconf}))
  _extra_incpaths+=("-I")
  _extra_incpaths+=("${MINGW_PREFIX}/include/mariadb")

# This *could* be used but we'd have to make sure it's correct for all variants first.
#  local -a _extra_libpaths=($(pkg_config_qt5 --libs-only-L dbus-1 libxml-2.0 freetype2))
#  local -a _extra_libs=($(pkg_config_qt5 --libs-only-l dbus-1 libxml-2.0 freetype2))
  local -a _extra_libpaths=()
  local -a _extra_libs=()

  if [ "${_variant}" = "-static" ]; then
    if [ ${_qt_version:0:3} = "5.6" ]; then
      _extra_libs+=("-l" "iphlpapi")      # Needed after linking static dbus library
    fi
  fi

  export PATH="${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}"

  if [ "${_variant}" = "-shared" ]; then
    # This export breaks the static library build in 5.9.0;
    # Causes the DBUS_LIBS setting passed to configure to be ignored.
    export PKG_CONFIG="${MINGW_PREFIX}/bin/pkg-config.exe"
  fi

  # Set other config stuff that's configure-script-type dependent.
  local -a _extra_config
  if [ "${_configure}" = "./configure" ]; then
    _extra_config+=("-no-glib")
  else
    _extra_config+=("-make-tool" "make")
  fi

  # Determine the SQL driver configuration, variant dependent.
  # static can't use anything but -qt-sql-sqlite both for size
  # reasons and because shared libraries get auto-detected and
  # built as plugins.
  local -a _sql_config
  if [ "${_variant}" = "-static" ]; then
    _sql_config+=("-no-sql-ibase")
    _sql_config+=("-no-sql-mysql")
    _sql_config+=("-no-sql-odbc")
    _sql_config+=("-no-sql-psql")
    _sql_config+=("-no-sql-sqlite2")
    if [[ ${_qt_version:0:3} != "5.6" ]] ; then
      _sql_config+=("-sql-sqlite")
      _sql_config+=("-qt-sqlite")
    fi
  else
    if [[ ${_qt_version:0:3} != "5.6" ]]; then
      _sql_config+=("-plugin-sql-ibase")
    fi
    _sql_config+=("-plugin-sql-psql")
    _sql_config+=("-plugin-sql-mysql")
    _sql_config+=("-plugin-sql-odbc")
  fi

  # Qt manages the compiler flags for release / debug configs separately, so having our own values (-O2) is harmful here ..
  unset CFLAGS
  unset CXXFLAGS
  unset LDFLAGS
  unset QMAKESPEC
  unset XQMAKESPEC
  unset QMAKEPATH
  unset QMAKEFEATURES

  local -a configure_opts

  if [ "${_variant}" = "-static" ]; then
    configure_opts+=("-static")
    configure_opts+=("-D" "DBUS_STATIC_BUILD")
    configure_opts+=("-D" "JAS_DLL=0")
    configure_opts+=("-openssl-linked" "OPENSSL_LIBS=-L${MINGW_PREFIX}/lib -lssl -lws2_32 -lgdi32 -lcrypt32 -lcrypto -lws2_32 -lgdi32 -lcrypt32")
    if [[ ${_qt_version:0:3} != "5.6" ]] ; then
      configure_opts+=("-dbus" "DBUS_LIBS=-ldbus-1 -lws2_32 -liphlpapi")
    else
      configure_opts+=("-dbus")
    fi
    configure_opts+=("-no-fontconfig")
    configure_opts+=("-no-icu")
    configure_opts+=("-qt-zlib")
    configure_opts+=("-qt-pcre")
    configure_opts+=("-qt-libpng")
    configure_opts+=("-qt-libjpeg")
    configure_opts+=("-qt-harfbuzz")
    configure_opts+=("-qt-freetype")
  else
    configure_opts+=("-shared")
    if [[ "$_with_fontconfig" == "no" ]]; then
      configure_opts+=("-no-fontconfig")
    fi
    if [[ "$_with_openssl" == "no" ]]; then
      configure_opts+=("-no-openssl")
    fi
    if [[ "$_with_dbus" == "no" ]]; then
      configure_opts+=("-no-dbus")
    else
      configure_opts+=("-dbus")
    fi
    if [[ "$_system_freetype" == "yes" ]]; then
      configure_opts+=("-system-freetype")
    fi
    if [[ "$_system_harfbuzz" == "yes" ]]; then
      configure_opts+=("-system-harfbuzz")
    else
      configure_opts+=("-qt-harfbuzz")
    fi
    if [[ "$_system_libjpeg" == "no" ]]; then
      configure_opts+=("-qt-libjpeg")
    fi
    if [[ "$_system_libpng" == "no" ]]; then
      configure_opts+=("-qt-libpng")
    fi
    if [[ "$_system_zlib" == "no" ]]; then
      configure_opts+=("-qt-zlib")
    fi
    if [[ "$_system_pcre2" == "no" ]]; then
      configure_opts+=("-qt-pcre")
    fi
    if [[ "$_with_icu" == "yes" ]]; then
      configure_opts+=("-icu")
    else
      configure_opts+=("-no-icu")
    fi
  fi

  if [[ "$_build_examples" == "no" ]]; then
    configure_opts+=("-nomake" "examples")
  fi
  if [[ "$_build_tests" == "no" ]]; then
    configure_opts+=("-nomake" "tests")
  fi
  if [[ "$_build_tools" == "no" ]]; then
    configure_opts+=("-skip" "qttools")
  fi
  if [[ "$_build_multimedia" == "no" ]]; then
    configure_opts+=("-skip" "qtmultimedia")
  else
    if [[ ${_qt_version:0:3} != "5.6" ]] ; then
      configure_opts+=("-no-gstreamer")
    fi
  fi
  if [[ "$_build_imageformats" == "no" ]]; then
    configure_opts+=("-skip" "qtimageformats")
  fi
  if [[ "$_build_script" == "no" ]]; then
    configure_opts+=("-skip" "qtscript")
  fi
  if [[ "$_build_xmlpatterns" == "no" ]]; then
    configure_opts+=("-skip" "qtxmlpatterns")
  fi
  if [[ "$_build_declarative" == "no" ]]; then
    configure_opts+=("-skip" "qtdeclarative")
  fi
  if [[ "$_build_datavis3d" == "no" ]]; then
    configure_opts+=("-skip" "qtdatavis3d")
  fi
  if [[ "$_build_activeqt" == "no" ]]; then
    configure_opts+=("-skip" "qtactiveqt")
  fi
  if [[ "$_build_serialport" == "no" ]]; then
    configure_opts+=("-skip" "serialport")
  fi
  if [[ "$_build_svg" == "no" ]]; then
    configure_opts+=("-skip" "qtsvg")
  fi
  if [[ "$_build_connectivity" == "no" ]]; then
    configure_opts+=("-skip" "qtconnectivity")
  fi
  if [[ "$_build_location" == "no" ]]; then
    configure_opts+=("-skip" "qtlocation")
  fi
  if [[ "$_build_charts" == "no" ]]; then
    configure_opts+=("-skip" "qtcharts")
  fi
  if [[ "$_build_sensors" == "no" ]]; then
    configure_opts+=("-skip" "qtsensors")
  fi
  if [[ "$_build_websockets" == "no" ]]; then
    configure_opts+=("-skip" "qtwebsockets")
  fi
  if [[ "$_build_gamepad" == "no" ]]; then
    if [[ ${_qt_version:0:3} != "5.6" ]] ; then
      configure_opts+=("-skip" "qtgamepad")
    fi
  fi
  if [[ "$_build_webchannel" == "no" ]]; then
    configure_opts+=("-skip" "qtwebchannel")
  fi
  if [[ "$_build_winextras" == "no" ]]; then
    configure_opts+=("-skip" "qtwinextras")
  fi


#  make confclean # May be needed while doing configure changes.

  ${_configure} \
    -prefix ${QTDIR_WIN} \
    -datadir ${QTDIR_WIN}/share/qt5 \
    -archdatadir ${QTDIR_WIN}/share/qt5 \
    -examplesdir ${QTDIR_WIN}/share/qt5/examples \
    -testsdir ${QTDIR_WIN}/share/qt5/tests \
    -opengl desktop \
    -opensource \
    -confirm-license \
    -platform win32-g++ \
    "${_build_mode}" \
    "${_extra_incpaths[@]}" \
    "${_extra_libpaths[@]}" \
    "${_extra_libs[@]}" \
    -no-iconv \
    "${_extra_config[@]}" \
    "${_sql_config[@]}" \
    "${configure_opts[@]}"

  # There is a race condition / dependency problem with libqtiff and dumpdoc.exe which
  # can happen at -j9 so make twice (dumpdoc.exe depends on libqtiff but can get built
  # first).
  make ${MAKEFLAGS} || make ${MAKEFLAGS}
  # For quicker turn-around testing qtactiveqt for race issue in static build.
  # rm -fr qtimageformats/plugins/imageformats
  # make module-qtbase
  # make -j1 module-qtactiveqt
  # exit 1
}

package() {

  cd ${srcdir}
  cd ${CARCH}

  export PATH=${pkgdir}${_qt5_prefix}/bin:${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}

  make install
  if [[ "$_make_docs" == "yes" ]]; then
    make docs
    make install_qch_docs
  fi

  install -D -m644 LGPL_EXCEPTION.txt "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LGPL_EXCEPTION.txt

  # Remove dlls from lib/
  rm -f "${pkgdir}${_qt5_prefix}/lib"/*.dll

  # Workaround for installing empty .pc files
  plain "---> Fix pkgconfig files..."
  local _pc_files=( $(find ${srcdir}/${CARCH} -type f -name Qt5*.pc) )
  cp -f ${_pc_files[@]} ${pkgdir}${_qt5_prefix}/lib/pkgconfig/

  # Fix paths in qconfig.pri and qmodule.pri:
  #   $(cygpath -m ${MINGW_PREFIX}) -> $(cygpath -m ${pkgdir}${MINGW_PREFIX})
  MINGW_PREFIX_WIN=$(cygpath -m ${_qt5_prefix})
  PKGDIR_MINGW_PREFIX_WIN=$(cygpath -m ${pkgdir}${_qt5_prefix})
  find "${pkgdir}${_qt5_prefix}/share/qt5" -type f -name '*.pri' \
    -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${PKGDIR_MINGW_PREFIX_WIN}|g" {} \;
}

sha256sums=(
  '609ab74b93ef11f24ef4d7c1bd0a2e81c4280b07fa455dfcf003a2364ab72745'  # 0001
  '571a2f0a60ca97bfa696b030c416ac04a11202b3f33eb93d582654209e1cdbbe'  # 0001
  '70938426942058ad66c1b9b304b12cfe7a85947712729a9b7235c86397cfc265'  # 0001
  '1b3aace0abc6c1ab1d077a57f7b2b0b7772e63c5b61519b633e955bbbc6d5485'  # 0002
  '231203cbb4112a2cc03452829663f9867ba5326b2901bc2f26f536ad1cfc8339'  # 0002
  '12263a04ef371f5a934b43bef7b8607cb7aa8a6d6da69a75a5411da6d44368d6'  # 0003
  '91b9e23592cc1042fde7ee43a828be695da91c5575803924897eac2a3bef8853'  # 0003
  '334e8f84b892e1bda5d71ec078d6e2a325d979f0d3ab454fe348594d1c039f84'  # 0005
  'c01e095a624f8fb7527ac0a1f476d5b395c55a7abc8618d69c09c503caca86ea'  # 0006
  '02d007a0a735f6b41e4feab7f0cc30a5bf8e55d413513177f9513eff0dfd55d8'  # 0007
  '1d8ac1807437f2ac6fa7b25e173c3ca69dd32381e5b2fa501499f96972ad1d2e'  # 0007
  'b21726bbd2ed34ad78e18d6b82a2c3b3c3e753ee2e978a5bb58b386f1f33ce41'  # 0008
  '44dfc8b56be2d3f33bb7f67abd472a58380d22bc3532f3ecdabfb3dd108f4a77'  # 0011
  '66b6c6dac6b3c208d5930d12602e0d4a714d72fb881a5792bf966c0c46ab5aa9'  # 0011
  '193957a4fbd18cbe951dc11d836e1ff5d6ad07780643ef81e559d57f6672b028'  # 0012
  '539653bcce49d1841aba70b5753407f4e3d2232db77fc75381a9182dec76defe'  # 0014
  '84945d2b47e05465af08094fefa743bff12f1d842ec0524b61ff789cd0f2d0e5'  # 0015
  '7a85c145e2053f8ac48defa50b31ec9745cca62ed87284662b2b4661b25376ab'  # 0016
  '10dc3177cf7c76667e28fee51dc3b029ba1f0eff16901672b39250177fa20663'  # 0016
  '8048fe32b4f4155b1616dbd68e6e2fa4e01e7e0916d64664be24e7f21329c3f2'  # 0017
  '2c949e5fd0339892e5ea1253f233231c2e594783af517ae924b9b3c6799521da'  # 0024
  '200aab02ab07ea15b31efd54f4a1eee1e9ed65398edf392dde462288d47cb7a2'  # 0024
  'f3c5709803303cc411b8f4f0232cafa6f9b6b9c1f2d3791cb70415c6db0060b8'  # 0025
  '493c081dd06836baa28cac1f38b2d87b2f402670e442b8a163530d3f965cc5e1'  # 0025
  '6893c83e4d26643a1cf5607a1a367401d27fec98440fa1d3685a8cf1478ddf92'  # 0030
  '7f5e092a5062db776a96ab32758ff175c3689b79902f5d9656f31029c33f66dd'  # 0031
  '1ada266bc6cd033d770bc40ad879527db222563fc20cf98cf2848b84b2a0e503'  # 0034
  '27e9d402126d313ff647066207038578c26a3cf0f60833ae5d76157d53712eae'  # 0035
  '29f13f7b44476bebfc5280a8481fa24926185860476ed0fd05f6b5a959b801d8'  # 0036
  'c114d2df071b66e47f4bd43d335d48868fd5bcf9670f276b557edacd53fa92c0'  # 0037
  'b9939efea7792a960cdc9404a515c6f0a1cd42ffbdb018d52f2b0206fffe17f5'  # 0038
  '3ae9d64fb683036b3b1f91036378791e1ec4a10205c59e78761d22d8479c0540'  # 0039
  'd720ac76035d56caea1f045dfb468a25865f9d4b22016cec5414f1c639a7697a'  # 0040
  '914051840e01bf453e3db710d4471e6758e39e2cb87f8ffe3072fb90218c9f83'  # 0041
  '9eb9366d81179883e09e180bcd6bba3452661879f993a7e48e4c86d8bb4720e6'  # 0042
  '29ed4566d4c1853b70a5173c6391ed90f123c5121b5836f2d16f8478f6354f0a'  # 0043
  '72e46178f2f694d8408f22684d1a7d39394056cb574fc4855c1f38c9d51e7e6c'  # 0045
  'fd6b1cd956730c1a05a7489760afed6b36561a3b0ec5857c3fbe21dcd7a54617'  # 0046
  '3bda25f357a33b122345fea011a14199b5953fd248fab960a5344a2ed9401331'  # 0048
  '9dd8bb8d64d08bed96086dbd7d2b8ff0a5ea7f7672db65c45cab626b51f6061c'  # 0049
  'ca5a67f795f04ed0831dc6084affc3553b22ea9b6af6c11c15871415c81f6a04'  # 0049
  'f69b0391a523133ee5f1434c441736149976a0e8223de25ca1c1eed416fbf707'  # 0051
  'aff6c5fa28ab0a7e8b111f894bf167e949707b69bf1b45ebc48bb59194b714f9'  # 0051
  'e868da7e8716fd3f09d448d003796feda77e59b38d194cab7c8a99fabbdb78af'  # 0125
  'b6bfe63f370a8553f02145a4d412489e705bb00d1d3abcb321fe6a562f065bec'  # 0125
  '0f1dd2950ec0cfd0a4ceca746e7a09e3ee38e4abf6138f54b087b73e207b3233'  # 0300
)
