# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

# Please keep this file exactly the same (except _variant=)
# as {mingw-w64-qt5/PKGBUILD,mingw-w64-qt5-static/PKGBUILD}
#_variant=-static
_variant=-shared

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

# Tune the following to decide how and what to build
if [ "${_variant}" = "-static" ]; then
  _namesuff="-static"
  _with_icu=yes
  _with_fontconfig=no
  _with_openssl=yes
  _with_dbus=yes
  _system_freetype=no
  _system_zlib=no
  _system_pcre=no
  _system_libpng=no
  _system_libjpeg=no
  _system_harfbuzz=no
  _build_examples=no # examples result in > 100 GiB
  _build_tools=yes
  _build_tests=yes
  _make_docs=no # docs in shared qt5 are sufficient
#  _ltcg="yes"
  _ltcg="no"
else
  _namesuff=
  _with_icu=yes
  _with_fontconfig=yes
  _with_openssl=yes
  _with_dbus=yes
  _system_freetype=yes
  _system_zlib=yes
  _system_pcre=yes
  _system_libpng=yes
  _system_libjpeg=yes
  _system_harfbuzz=yes
  _build_examples=yes
  _build_tools=yes
  _build_tests=yes
  _make_docs=yes
  _ltcg=no
fi

# 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

# Using -O0 results in a Qt5WebKitd.dll that is > 2.5GB
# so force -Og. If you really need to, change this back
# to -O0, leave it blank or comment it out.
# Update: I think specifying anything here leads to huge
# Qt5WebKitd.dll, never commit with this set to anything
# -O0 is the default for GCC anyway, but qt5webkit seems
# to use a different flag if nothing explictly specified
# OPTIM_D="-Og"

# 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

# So that both configure shell script and configure.exe
# are tested on MSYS2, we use both depending on variant
if [ "${_variant}" = "-static" ]; then
  _configure=./configure
else
  _configure=./configure.bat
fi

# When using the configure bash script, MSYS2 make is
# probably a better choice as otherwise the Makefiles
# can have MSYS2 paths in them. We try to handle this
# but it is ad-hoc at best.
if [ "${_configure}" = "./configure" ]; then
  _make=make
else
  _make=make
#  _make=${MINGW_PREFIX}/bin/mingw32-make
fi

#_opengl=angle
_opengl=desktop
#_opengl=dynamic
_opengl_for_configure="${_opengl}"

_realname=qt5${_namesuff}
pkgbase="mingw-w64-${_realname}"
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
_ver_base=5.12.0
# use 5.6.1-1 hot fix : only the archive name was changed from *-5.6.1.tar.xz to *-5.6.1-1.tar.xz
_hotfix=
pkgver=${_ver_base//-/}
pkgrel=2
arch=('any')
pkgdesc="A cross-platform application and UI framework (mingw-w64${_namesuff})"
url='https://www.qt.io/'
install=qt5-${CARCH}.install
license=('GPL3' 'LGPL' 'FDL' 'custom')

# 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

depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-qtbinpatcher"
         "${MINGW_PACKAGE_PREFIX}-z3"
         $([[ "$_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") \
            "${MINGW_PACKAGE_PREFIX}-openal" \
            $([[ "$_system_pcre" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-pcre2") \
            "${MINGW_PACKAGE_PREFIX}-sqlite3" \
            "${MINGW_PACKAGE_PREFIX}-vulkan" \
            "${MINGW_PACKAGE_PREFIX}-xpm-nox" \
            $([[ "$_system_zlib" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-zlib"))
            $([[ "$_opengl" != "desktop" ]] && echo "${MINGW_PACKAGE_PREFIX}-angleproject-git")
            $([[ "$_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}-firebird2" \
            "${MINGW_PACKAGE_PREFIX}-postgresql")
           )
makedepends=("bison"
             "diffutils"
             "flex"
             "gperf"
             "m4"
             "make"
             "patch"
             "perl"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-clang"
             "${MINGW_PACKAGE_PREFIX}-clang-tools-extra"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python2"
             "${MINGW_PACKAGE_PREFIX}-ruby"
             "${MINGW_PACKAGE_PREFIX}-make"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             $([[ "$_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${_namesuff}" "${MINGW_PACKAGE_PREFIX}-qt5${_namesuff}")
options=('!strip' 'staticlibs' 'ccache')
_pkgfqn="qt-everywhere-src-${_ver_base}"
noextract=(${_pkgfqn}${_hotfix}.tar.xz)
source=(#https://download.qt.io/development_releases/qt/${pkgver%.*}/${_ver_base//RC/rc}/single/${_pkgfqn}.tar.xz
        https://download.qt.io/official_releases/qt/${pkgver%.*}/${_ver_base}${_hotfix}/single/${_pkgfqn}${_hotfix}.tar.xz
        #https://download.qt.io/community_releases/${pkgver%.*}/${_ver_base}-final/qtwebkit-opensource-src-${_ver_base}.tar.xz
        #https://download.qt.io/snapshots/qt/${pkgver%.*}/${_ver_base}/2014-05-07_85/src/qt-everywhere-opensource-src-${_ver_base}.tar.xz
        0001-Add-link-time-optimization-support-for-Clang-GCC-and.patch
        0001-qt-5.8.0-fix-sql-libraries-mingw.patch
        0002-qt-5.8.0-configure-gcc-before-clang.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
        0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch
        0009-qt-5.3.0-qmlimportscanner-Ensure-the-correct-variant-is-run.patch
        0010-qt-5.3.0-qdoc-increase-stack-size-for-win32-g-too.patch
        0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch
        0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch
        0017-qt-5.3.0-fix-examples-building.patch
        0020-qt-5.3.0-use-external-angle-library.patch
        0023-qt-5.3.0-env-set-external-angle.patch
        0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
        0025-qt-5.8.0-force-using-make-on-msys.patch
        0028-qt-5.8.0-Revert-untangle-use-of-system-vs.-shell-path-list-se.patch
        0029-qt-5.8.0-Revert-fix-quoting-and-path-separators-in-qtPrepareT.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
        0044-qt-5.4.0-win32-g++-enable-qtwebengine-build.patch
        0046-qt-5.4.1-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
        0050-qt-5.5.1-fix-the-trailing-backslash-in-DESTDIR-on-mingw-worka.patch
        0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch
        0052-qt-5.11-mingw-fix-link-qdoc-with-clang.patch
        0053-qt-5.11-documents-fix-regression.patch
        0054-win32-dont-need-flatpack-theme.patch
        0055-resolve-conflict-with-vectorcanbackend-static.patch
        0056-qt-5.11-static_icu.patch
        0125-qt5-windeployqt-fixes.patch
        0300-qt-5.8.0-cast-errors.patch
        0301-remove-evr-declaration.patch
        qml_static_plugins.patch)

# 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=$(${MINGW_PREFIX}/bin/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[@]}"
}

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  [[ -d ${srcdir}/${_pkgfqn} ]] && rm -rf ${srcdir}/${_pkgfqn}
  tar -xJf ${srcdir}/${_pkgfqn}${_hotfix}.tar.xz -C ${srcdir} --exclude=${_pkgfqn}/{qtandroidextras,qtmacextras,qtwayland,qtwebengine,qtx11extras} || true

  cd ${srcdir}/${_pkgfqn}

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

  apply_patch_with_msg \
    0001-qt-5.8.0-fix-sql-libraries-mingw.patch \
    0002-qt-5.8.0-configure-gcc-before-clang.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 \
    0008-qt-5.3.0-win32-g-Add-QMAKE_EXTENSION_IMPORTLIB-defaulting-to-.patch \
    0011-qt-5.8.0-mingw-dbus-and-pkg-config.patch \
    0016-qt-5.8.0-win32-g++-use-qpa-genericunixfontdatabase.patch \
    0017-qt-5.3.0-fix-examples-building.patch

  if [ "${_opengl}" != "desktop" ]; then
    # Hacks to use external ANGLE libraries.
    # These patches needs more work - they're unfinished and break desktop OpenGL
    apply_patch_with_msg \
      0020-qt-5.3.0-use-external-angle-library.patch \
      0023-qt-5.3.0-env-set-external-angle.patch
    if [ "${_configure}" = "./configure" ]; then
      _opengl_for_configure=yes
    fi
  fi

  # patch -p1 -i ${srcdir}/0024-qt-5.3.0-icu-add-U_LIB_SUFFIX_C_NAME.patch
  if [ "${_make}" = "make" ]; then
    apply_patch_with_msg \
      0025-qt-5.8.0-force-using-make-on-msys.patch
  fi

  # Ossi says we should fix this in qwebkit with a $$(shell_path), but the ' quotes get in the way
  # due to qtPrepareTool adding them with $$shell_quote
  apply_patch_with_msg \
    0028-qt-5.8.0-Revert-untangle-use-of-system-vs.-shell-path-list-se.patch \
    0029-qt-5.8.0-Revert-fix-quoting-and-path-separators-in-qtPrepareT.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

  # Patches so that qt5-static can be used with cmake.
  apply_patch_with_msg \
    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

  # More odds and sods.
  # patch -p1 -i ${srcdir}/0044-qt-5.4.0-win32-g++-enable-qtwebengine-build.patch

  apply_patch_with_msg \
    0046-qt-5.4.1-Revert-Revert-fix-NTFS-mount-points.patch

  apply_patch_with_msg \
    0048-qt-5.4.2-win32-Avoid-platformNativeInterface-segfaults-with-minimal-platform.patch \
    0049-qt-5.8.0-win32-do-not-use-fontconfig.patch \
    0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch \
    0052-qt-5.11-mingw-fix-link-qdoc-with-clang.patch \
    0053-qt-5.11-documents-fix-regression.patch \
    0054-win32-dont-need-flatpack-theme.patch \
    0055-resolve-conflict-with-vectorcanbackend-static.patch \
    0056-qt-5.11-static_icu.patch \
    0125-qt5-windeployqt-fixes.patch \
    0300-qt-5.8.0-cast-errors.patch \
    0301-remove-evr-declaration.patch

  # See: https://bugreports.qt.io/browse/QTBUG-37902
  # _ver_num=${_ver_base%%-*}
  # sed -i "s/^MODULE_VERSION = .*$/MODULE_VERSION = ${_ver_num}/g" qtenginio/.qmake.conf

  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

  # To keep the build folder name quite small (PATH_MAX limit)
  # the source folder (long) is renamed to $CARCH (i686 or x86_64)
  cd ${srcdir}
  [[ -d ${CARCH} ]] && rm -rf ${CARCH}
  sleep 5
  mv ${_pkgfqn} ${CARCH}
}

build() {
  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 _libxml2_pkgconf=""
  if [ "${_variant}" = "-shared" ]; then
    _libxml2_pkgconf="libxml-2.0"
  fi

  local -a _extra_incpaths=($(pkg_config_qt5 --cflags-only-I dbus-1 ${_libxml2_pkgconf} ${_freetype2_pkgconf}))
  if [ "${_opengl}" != "desktop" ]; then
    export EXTERNAL_ANGLE=1
    _extra_incpaths+=("-I")
    _extra_incpaths+=("${MINGW_PREFIX}/include/GLSLANG")
  fi
  _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=()

  export PATH="${srcdir}/${CARCH}/qtbase/bin:${srcdir}/${CARCH}/qtbase/lib:${PATH}"
  export LLVM_INSTALL_DIR=${MINGW_PREFIX}
  export FORCE_MINGW_QDOC_BUILD=1
  export QDOC_USE_STATIC_LIBCLANG=1

  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

  # Workaround for building QtWebkit
  #pushd ${srcdir}/${CARCH}/qtwebkit > /dev/null
  #  mkdir .git
  #  /usr/bin/perl ${srcdir}/${CARCH}/qtbase/bin/syncqt.pl Source -version ${pkgver}
  #  rm -rf .git
  #popd > /dev/null

  cd ${CARCH}
  touch qtbase/.gitignore

  # 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")
    _extra_config+=("${_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")
    _sql_config+=("-sql-sqlite")
    _sql_config+=("-qt-sqlite")
  else
    _sql_config+=("-plugin-sql-ibase")
    _sql_config+=("-plugin-sql-psql")
    _sql_config+=("-plugin-sql-mysql")
    _sql_config+=("-plugin-sql-odbc")
  fi

  if [ "${_variant}" = "-static" ]; then
    export OPENSSL_LIBS="-lssl -lcrypto -lcrypt32 -lgdi32"
  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
# export NINJA_PATH=${MINGW_PREFIX}/bin/ninja.exe

  local -a configure_opts

  if [ "${_variant}" = "-static" ]; then
    configure_opts+=("-static")
    configure_opts+=("-D" "DBUS_STATIC_BUILD")
    configure_opts+=("-D" "JAS_DLL=0")
    if [ "$_with_dbus" == "yes" ]; then
      configure_opts+=("-dbus-linked" "DBUS_LIBS=-ldbus-1 -lws2_32 -liphlpapi")
    else
      configure_opts+=("-no-dbus")
    fi
    if [ "$_with_openssl" == "yes" ]; then
      configure_opts+=("-openssl-linked")
    else
      configure_opts+=("-no-openssl")
    fi
  else
    configure_opts+=("-shared")
    if [ "$_with_dbus" == "yes" ]; then
      configure_opts+=("-dbus")
    else
      configure_opts+=("-no-dbus")
    fi
    if [ "$_with_openssl" == "no" ]; then
      configure_opts+=("-no-openssl")
    fi
  fi

  if [ "$_with_fontconfig" == "no" ]; then
    configure_opts+=("-no-fontconfig")
  fi
  if [ "$_system_freetype" == "yes" ]; then
    configure_opts+=("-system-freetype")
  else
    configure_opts+=("-qt-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_pcre" == "no" ]; then
    configure_opts+=("-qt-pcre")
  fi
  if [ "$_with_icu" == "yes" ]; then
    configure_opts+=("-icu")
  else
    configure_opts+=("-no-icu")
  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

  ${_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 ${_opengl_for_configure} \
    -opensource \
    -confirm-license \
    -platform win32-g++ \
    "${_build_mode}" \
    "${_extra_incpaths[@]}" \
    "${_extra_libpaths[@]}" \
    "${_extra_libs[@]}" \
    -no-iconv \
    -no-gstreamer \
    "${_extra_config[@]}" \
    "${_sql_config[@]}" \
    "${configure_opts[@]}"

  # I'm keeping this around while qt5-static cmake problems persist (hopefully not long!)
  # qtbase/mkspecs/modules-inst/qt_lib_core.pri
  # pushd src/x86_64
  #   ROOT=$(pwd -W)
  #   pushd qtbase/
  #     ${ROOT}/qtbase/bin/qmake.exe ${ROOT}/qtbase/qtbase.pro -o Makefile
  #   popd
  #   cp -rf qtbase/src/corelib qtbase/src/corelib.pre-write-cmake
  #   pushd qtbase/src/corelib
  #     ${ROOT}/qtbase/bin/qmake.exe ${ROOT}/qtbase/src/corelib/corelib.pro -d -d -d -d -o Makefile > log.txt
  #   popd
  # popd
  # .
  # .. or .. (this alternative could be used when _minimal=yes)
  # .
  # pushd src/x86_64
  #   ${_make} module-qtbase && ${_make} module-qtbase-install_subtargets
  # popd
  # .. do your testing.
  # 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 qtwebengine.
  # ${_make} module-qtbase
  # ${_make} module-qtwebengine
  # exit 1

  # Fix paths
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qdoc|${QTDIR}/qtbase/bin/qdoc|g" {} +
  # find "${QTDIR}" -name Makefile -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # find "${QTDIR}" -name Makefile.qmake-docs -exec sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" {} +
  # sed -i "s|/usr/lib/qt/bin/qhelpgenerator|${QTDIR}/qttools/bin/qhelpgenerator|g" qtwebkit/Source/Makefile.api
}

check() {
  cd ${CARCH}
  make check -j1 -k
}

package() {

  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 LICENSE.FDL     "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.FDL
  install -D -m644 LICENSE.GPLv2   "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.GPLv2
  install -D -m644 LICENSE.GPLv3   "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.GPLv3
  install -D -m644 LICENSE.LGPLv21  "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.LGPLv21
  install -D -m644 LICENSE.LGPLv3  "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.LGPLv3
  install -D -m644 LICENSE.QT-LICENSE-AGREEMENT-4.0  "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.QT-LICENSE-AGREEMENT-4.0

  # 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 wrong path in prl files
  # find "${pkgdir}${_qt5_prefix}/lib" -type f -name '*.prl' \
  #   -exec sed -i -e '/^QMAKE_PRL_BUILD_DIR/d;s/\(QMAKE_PRL_LIBS =\).*/\1/' {} \;

  # Fix wrong qmake path in pri file
  # sed -i "s|${srcdir}/${CARCH}/qtbase|/usr|" \
  #   "${pkgdir}"/usr/lib/qt/mkspecs/modules/qt_lib_bootstrap_private.pri

  # 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" {} \;

  # https://github.com/Alexpux/MINGW-packages/issues/1942
  if [ "${_variant}" = "-static" ]; then
    cd ${pkgdir}${_qt5_prefix}
    patch -p1 -i ${srcdir}/qml_static_plugins.patch
    rm -v "lib/cmake/Qt5Gui/Qt5Gui_QVirtualKeyboardPlugin.cmake"
  fi
}

# return 0
# And now for something completely broken:
# https://bugreports.qt.io/browse/QTBUG-40814
# Using this:
# https://www.mirrorservice.org/sites/download.qt-project.org/snapshots/qt/5.3/5.3.2/2014-09-12_151/qt-opensource-windows-x86-msvc2013_64-5.3.2_2014-09-12_10-11-49-151.exe
# and:
# https://www.mirrorservice.org/sites/download.qt-project.org/snapshots/qt/5.3/5.3.2/2014-09-12_src/qt-everywhere-opensource-src-5.3.2.zip
# ..  unpacked into C:\work\build\qt5_workdir\w\s
# On MinGW-w64, both debug and release fail .. release has an extra segfault though quite early on.
# pushd /e/m2/repo/mingw-w64-qt5/src/x86_64/qtscript/tests
# export PATH=/mingw64/bin:$PATH
# export PKG_CONFIG_PATH=/mingw64/lib/pkgconfig
# for CONFIG in debug release; do
#   [ -d ${CONFIG} ] && rm -rf ${CONFIG}
#   mkdir ${CONFIG}
#   pushd ${CONFIG}
#   qmake -r CONFIG+=${CONFIG} ../
#   make -j12
#   ls -l ./auto/qscriptjstestsuite/${CONFIG}/tst_qscriptjstestsuite.exe    > qscriptjstestsuite.log
#   ./auto/qscriptjstestsuite/${CONFIG}/tst_qscriptjstestsuite.exe -silent >> qscriptjstestsuite.log
#   popd
# done

# i686 build failure with yarr:
# export PATH=/mingw32/bin:$PATH
# export PKG_CONFIG_PATH=/mingw32/lib/pkgconfig
# pushd /e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml
# make
# make[4]: Entering directory '/e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml'
# g++ -Wl,-s -shared -Wl,--out-implib,E:/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/lib/libQt5Qml.dll.a -o ../../lib/Qt5Qml.dll object_script.Qt5Qml.Release  -lshell32 -LE:/m2/repo/mingw-w64-qt5/src/i686/qtbase/lib -lQt5Network -lQt5Core .obj/release/Qt5Qml_resource_res.o
# ./.obj/release/YarrInterpreter.o:YarrInterpreter.cpp:(.text+0x622): undefined reference to `JSC::Yarr::wordcharCreate()'
# ./.obj/release/YarrInterpreter.o:YarrInterpreter.cpp:(.text+0x693): undefined reference to `JSC::Yarr::newlineCreate()'
# E:/msys64/mingw32/bin/../lib/gcc/i686-w64-mingw32/4.9.1/../../../../i686-w64-mingw32/bin/ld.exe: ./.obj/release/YarrInterpreter.o: bad reloc address 0x12 in section `.text$_ZN3WTF15BumpPointerPool6createEj[__ZN3WTF15BumpPointerPool6createEj]'
# collect2.exe: error: ld returned 1 exit status
# Makefile.Release:534: recipe for target '../../lib/Qt5Qml.dll' failed

# pushd /e/m2/repo/mingw-w64-qt5/src/i686/qtdeclarative/src/qml
# export PATH=/mingw32/bin:$PATH
# export PKG_CONFIG_PATH=/mingw32/lib/pkgconfig
# E:/m2/repo/mingw-w64-qt5/src/i686/qtbase/bin/qmake.exe -o Makefile qml.pro

sha256sums=('356f42d9087718f22f03d13d0c2cdfb308f91dc3cf0c6318bed33f2094cd9d6c'
            '7363ae7695af2f5278e9d91f6e52b3533dea4139ef252284bb82abfd025630d9'
            '70938426942058ad66c1b9b304b12cfe7a85947712729a9b7235c86397cfc265'
            '52a8c1ac8511643a10eb9b3b80b6881ecb3d08d4b5b9b730d16da461a40c4aa6'
            'e6c514784e6de3fb0ef26ad262ddc0f410eba540563fe61a480f938a8da4b395'
            '334e8f84b892e1bda5d71ec078d6e2a325d979f0d3ab454fe348594d1c039f84'
            '1b615ac7425fb7dc81d072f4c48e96d6fe0df5dcdeced61341aa3ca44c365e2b'
            '5a16a3ca18fb1fe990b4131f3c2c6d2f845e62db45225d9a0db58cf92e46bad9'
            '6d6621eaeee7b400c0b47d4660c433c1b3906600bfbda1e85116590497fe5889'
            '310db3f07db047d3303c2cff3106501a5aa242c56207af49fd06056d9bb8c880'
            '2f650101081cee4901f3a8e1116ec446062077bb7a0fa9b5a7f643a59dcbc932'
            '66b6c6dac6b3c208d5930d12602e0d4a714d72fb881a5792bf966c0c46ab5aa9'
            '138c46ef95921a0f3a43912d95268675b0dc671410d8099c3fcc3badabbbdb5b'
            '0829de00eaf63f1da83f734062639070e5ee3f522abef8823991a2d87782f4f8'
            'e0e029c97ebe41abdcbb2beec779b75657c1ecc15e0211d5db69111a3750268d'
            'd0dbe4b5f8a9291a02f9e9c6e59a0ff038e5dc521f79eb2da7a5fcaa681479bb'
            'd7c228df3cc680793a6c858e1fac01092c0877071c075804b7e93f6b3a481eae'
            '493c081dd06836baa28cac1f38b2d87b2f402670e442b8a163530d3f965cc5e1'
            '4130d55caba2a1761fe37c998c6b56409066edfd3a145e3cec8049fb883ce343'
            '6126c7559e9af1dec4cd66a31e9ff5db35e4c7c0fdb3ae0776feab6566167f7e'
            'a4721e46c10dc24d2ec91fb5aedffd940f444f227a20ecb6454565c4f76340c6'
            '7f5e092a5062db776a96ab32758ff175c3689b79902f5d9656f31029c33f66dd'
            '1ada266bc6cd033d770bc40ad879527db222563fc20cf98cf2848b84b2a0e503'
            '532d4c28a3574bd98af712eaf2fbb9768ea12cd2f597ac485d85aa5ccd0bf2e0'
            '799af493e184e2e3a070e80bedf62417ff617de8f02e18b9fa20c7563dd9d93c'
            'c114d2df071b66e47f4bd43d335d48868fd5bcf9670f276b557edacd53fa92c0'
            'cc250953ee8b79c03fbaf3d1797a188413d2ea9323769e49d8124a17af7852c8'
            '3ae9d64fb683036b3b1f91036378791e1ec4a10205c59e78761d22d8479c0540'
            'd720ac76035d56caea1f045dfb468a25865f9d4b22016cec5414f1c639a7697a'
            '914051840e01bf453e3db710d4471e6758e39e2cb87f8ffe3072fb90218c9f83'
            'a6c9ce0df1e378ef92e5fbab2891c5b0e4783498406ac3e33c3aea68a06d810d'
            '29ed4566d4c1853b70a5173c6391ed90f123c5121b5836f2d16f8478f6354f0a'
            '7d7a99ff45c6ae4f39be663d52bafc125970787f364e84593117e6a7d79f7eae'
            '7cf96e82099d8be12fb71102a6ee85c614fe6510c88e4e5d16165af63d69494c'
            'e142c1b385cf375eca4797dd8dd864f28a7c02fe8d7fae86be326d7775d0a1df'
            'f1ea27aa8b1febe7b806e775a928e2b03edc9a7045f6c03da3a7f57563b05e56'
            '234d1b207eb9ea11839f941799daf613028f33dbc89bebdf78b9a2dd4dd84dd2'
            '227940744aa3d87f51d9ea9d2fff0bfc11cda5f5055687bceb1c93ade5d5cdf6'
            '976132c3bc73ff7641566e2c0a127810bcf8c607da4158c659613bd06ba69437'
            '89fd6085f7fb85086692037338a935354fc68735bfb7c8423e282f99076250a3'
            '09346761413824d20da9570a8615facebcb6d2930b609ddc259e61063ee2d9bd'
            '09a4181ee02df575c13c94da7d7bc09c18252db9040bdaa27012e3aac7a947e1'
            'f414ceb01d4057147538f66b03f184be66a96d5b06f3dfd5aa086cd4de57ae0d'
            'bdc64610c6bc4a1ea58208d414b819432f4f7149a7ba00e79a94ed0177600e7e'
            'b38c912a1a0e94ea1a4f3706d84b5a6b2a46b72a9b3b5e6a821b123794fd5e07'
            '314a0c55c3ad45b46375c86717abaaa6cafd8a1cd41c09c77752503359ca6fb9'
            '670161ba661ea3dccd883473e39aaecb683a3c92da73502dc6939d496507532c')
