# 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

# Tune the following to decide how and what to build
if [ "${_variant}" = "-static" ]; then
  _namesuff="-static"
  _build_mode=("-debug-and-release")
  _with_icu=no
  _with_fontconfig=no
  _with_openssl=no
  _with_dbus=yes
  _system_freetype=no
  _system_zlib=yes
  _system_pcre=no
  _system_libpng=no
  _system_libjpeg=no
  _system_harfbuzz=no
  _system_assimp=no
  _system_doubleconversion=no
  _system_libtiff=no
  _system_libwebp=no
  _build_examples=no # examples result in > 100 GiB
  _build_tools=yes
  _build_tests=no
  _make_docs=no # docs in shared qt5 are sufficient
#  _ltcg="yes"
  _ltcg="no"
else
  _namesuff=
  _build_mode=("-release" "-force-debug-info" "-separate-debug-info")
  _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
  _system_assimp=yes
  _system_doubleconversion=yes
  _system_libtiff=yes
  _system_libwebp=yes
  _build_examples=no
  _build_tools=yes
  _build_tests=no
  _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

# hardening (ASLR, High entropy ASLR, DEP)
_enable_hardening=yes

# 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}"
if [ "${_variant}" = "-static" ]; then
  pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
else
  pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}" "${MINGW_PACKAGE_PREFIX}-${_realname}-debug")
fi
_ver_base=5.15.2
# 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')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
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 \
            $([[ "$_system_assimp" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-assimp") \
            $([[ "$_system_doubleconversion" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-double-conversion") \
            $([[ "$_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") \
            $([[ "$_system_libtiff" == "yes" ]] && echo "${MINGW_PACKAGE_PREFIX}-libtiff") \
            "${MINGW_PACKAGE_PREFIX}-libxml2" \
            "${MINGW_PACKAGE_PREFIX}-libxslt" \
            $([[ "$_system_libwebp" == "yes" ]] && echo "${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"))
            $([[ "$_with_icu" == "yes" ]] && echo \
              "${MINGW_PACKAGE_PREFIX}-icu" \
              "${MINGW_PACKAGE_PREFIX}-icu-debug-libs")
        )
optdepends=($([[ "$_variant" == "-shared" ]] && echo \
              "${MINGW_PACKAGE_PREFIX}-clang" \
              "${MINGW_PACKAGE_PREFIX}-libmariadbclient" \
              "${MINGW_PACKAGE_PREFIX}-firebird2" \
              "${MINGW_PACKAGE_PREFIX}-postgresql")
            )
makedepends=("bison"
             "diffutils"
             "flex"
             "gperf"
             "m4"
             "make"
             "patch"
             "perl"
             "rsync"
             "unzip"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-clang"
             "${MINGW_PACKAGE_PREFIX}-clang-tools-extra"
             "${MINGW_PACKAGE_PREFIX}-fxc2"
             "${MINGW_PACKAGE_PREFIX}-pkg-config"
             "${MINGW_PACKAGE_PREFIX}-python"
             "${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
        0000-adjust-qmake-conf-mingw.patch
        0001-qt-5.8.0-fix-sql-libraries-mingw.patch
        0002-qt-5.8.0-configure-gcc-before-clang.patch
        0004-fix-linking-again-different-static-libs.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
        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
        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
        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
        0051-qt-5.9.1-disable-qtlocation-mapboxgl-plugin.patch
        0052-qt-5.11-mingw-fix-link-qdoc-with-clang.patch
        0054-win32-dont-need-flatpack-theme.patch
        0056-qt-5.11-static_icu.patch
        0057-fix-and-enable-iconv-codec.patch
        0060-activeqt-handle-win64-in-dumpcpp.patch
        0062-fix-static-build-big-resources.patch
        0063-enable-mingw-schannel-alpn.patch
        0125-qt5-windeployqt-fixes.patch
        0300-qt-5.8.0-cast-errors.patch
        0302-ugly-hack-disable-qdoc-build.patch
        0304-qtdeclarative-disable-dx12.patch
        0310-fix-assimp-not-found.patch
        'fad2dc11.diff.zip::https://codereview.qt-project.org/changes/qt%2Fqtbase~333051/revisions/1/patch?zip')

# 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 \
    0000-adjust-qmake-conf-mingw.patch \
    0001-qt-5.8.0-fix-sql-libraries-mingw.patch \
    0002-qt-5.8.0-configure-gcc-before-clang.patch \
    0004-fix-linking-again-different-static-libs.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
  #  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 \
    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

  # 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 \
    0054-win32-dont-need-flatpack-theme.patch \
    0056-qt-5.11-static_icu.patch \
    0057-fix-and-enable-iconv-codec.patch \
    0060-activeqt-handle-win64-in-dumpcpp.patch \
    0062-fix-static-build-big-resources.patch \
    0063-enable-mingw-schannel-alpn.patch \
    0125-qt5-windeployqt-fixes.patch \
    0300-qt-5.8.0-cast-errors.patch \
    0304-qtdeclarative-disable-dx12.patch \
    0310-fix-assimp-not-found.patch

  # https://codereview.qt-project.org/c/qt/qtbase/+/333051
  cd qtbase
  apply_patch_with_msg fad2dc11.diff
  cd -

  # 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=
  local _HARD_FLAGS=
  case ${MINGW_CHOST} in
    i686*)
      _ARCH_TUNE="-march=i686 -mtune=core2"
      if [ "${_enable_hardening}" = "yes" ]; then
        _HARD_FLAGS="-Wl,--dynamicbase,--nxcompat,--no-seh"
      fi
    ;;
    x86_64*)
      _ARCH_TUNE="-march=nocona -mtune=core2"
      if [ "${_enable_hardening}" = "yes" ]; then
        _HARD_FLAGS="-Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high"
      fi
    ;;
  esac

  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
  sed -i "s|^QMAKE_LFLAGS           +=\(.*\)$|QMAKE_LFLAGS            += \1 ${LTCG_LFLAGS} ${_HARD_FLAGS}|g" qtbase/mkspecs/common/gcc-base.conf
  # But overwrite this one.
  #sed -i "s|^QMAKE_LFLAGS_RELEASE .*= \(.*\)$|QMAKE_LFLAGS_RELEASE    = ${QMAKE_LFLAGS_RELEASE}|g" qtbase/mkspecs/common/g++-win32.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

  _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}" = "-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 -lws2_32 -lcrypt32 -lgdi32"
  #fi

  # https://github.com/msys2/MSYS2-packages/issues/2282
  export MSYS2_ARG_CONV_EXCL='--foreign-types='

  # 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

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

  # Dont build qdoc utility for static package because of linking problems with clang
  if [ "${_variant}" = "-static" ]; then
    export QDOC_USE_STATIC_LIBCLANG=1
    # Hack to disable building qdoc
    patch -p1 -i ${srcdir}/0302-ugly-hack-disable-qdoc-build.patch
    export QDOC_SKIP_BUILD=1
  fi

  if [ "${_variant}" = "-static" ]; then
    configure_opts+=("-static")
    configure_opts+=("-no-jasper")
    configure_opts+=("-no-mng")
    #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+=("-schannel")
    fi
  else
    configure_opts+=("-shared")
    configure_opts+=("-jasper")
    configure_opts+=("-no-mng")
    if [ "$_with_dbus" == "yes" ]; then
      configure_opts+=("-dbus")
    else
      configure_opts+=("-no-dbus")
    fi
    if [ "$_with_openssl" == "no" ]; then
      configure_opts+=("-schannel")
    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_libtiff" == "yes" ]; then
    configure_opts+=("-system-tiff")
  else
    configure_opts+=("-qt-tiff")
  fi
  if [ "$_system_libwebp" == "yes" ]; then
    configure_opts+=("-system-webp")
  else
    configure_opts+=("-qt-webp")
  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 [ "$_system_assimp" == "yes" ]; then
    configure_opts+=("-system-assimp")
  else
    configure_opts+=("-qt-assimp")
  fi
  if [ "$_system_doubleconversion" == "yes" ]; then
    configure_opts+=("-system-doubleconversion")
  else
    configure_opts+=("-qt-doubleconversion")
  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 [ "${_opengl}" != "desktop" ]; then
  #  configure_opts+=("-angle")
  #  configure_opts+=("-combined-angle-lib")
  #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 \
    -no-wmf \
    "${_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_it() {

  cd ${CARCH}

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

  ${_make} install
  if [ "$_build_tools" == "yes" ]; then
    if [ "$_make_docs" == "yes" ]; then
      make docs
      make install_qch_docs
    fi
  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  "${pkgdir}${_qt5_prefix}"/share/licenses/qt5/LICENSE.QT-LICENSE-AGREEMENT

  mv -f "${pkgdir}${_qt5_prefix}/lib"/*.debug "${pkgdir}${_qt5_prefix}/bin"/ || true
  rsync -armR --remove-source-files --include="*/" --include="*.debug" --exclude="*" --prune-empty-dirs ${pkgdir}/.${MINGW_PREFIX} ${srcdir}/${CARCH}-debug/

  # Remove dlls from lib/
  rm -f "${pkgdir}${_qt5_prefix}/lib"/*.dll
  
  # Remove *.orig files
  find "${pkgdir}${_qt5_prefix}" -type f -name "*.orig" -exec rm -f {} \;

  # 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})
  local QT_PREFIX_WIN=$(cygpath -m ${_qt5_prefix})
  local PKGDIR_QT_PREFIX_WIN=$(cygpath -m ${pkgdir}${_qt5_prefix})
  local FAKE_PREFIX_FOR_REPLACE="@@QT_REAL_PREFIX/dir@@"
  local MINGW_PREFIX_WIN=$(cygpath -m ${MINGW_PREFIX})

  find "${pkgdir}${_qt5_prefix}/share/qt5" -type f \( -name '*.pri' -o -name '*.prl' \) \
      -exec sed -i -e "s|${QT_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}|g" {} \;

  find "${pkgdir}${_qt5_prefix}/lib" -type f \( -name '*.pri' -o -name '*.prl' \) \
      -exec sed -i -e "s|${QT_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}|g" {} \;

  find "${pkgdir}${_qt5_prefix}/lib" -type f -name '*.cmake' \
      -exec sed -i -e "s|${QT_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}|g" {} \;

  find "${pkgdir}${_qt5_prefix}/lib/pkgconfig" -type f -name '*.pc' \
      -exec sed -i -e "s|${QT_PREFIX_WIN}|${_qt5_prefix}|g" {} \;
      
  find "${pkgdir}${_qt5_prefix}/lib/pkgconfig" -type f -name '*.pc' \
      -exec sed -i -e "s|${PKGDIR_QT_PREFIX_WIN}|${_qt5_prefix}|g" {} \;

  if [ "${_variant}" = "-static" ]; then
    find "${pkgdir}${_qt5_prefix}/lib" -type f -name '*.cmake' \
      -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}/..|g" {} \;
    
    find "${pkgdir}${_qt5_prefix}/share/qt5" -type f \( -name '*.pri' -o -name '*.prl' \) \
      -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}/..|g" {} \;  
    
    find "${pkgdir}${_qt5_prefix}/lib" -type f \( -name '*.pri' -o -name '*.prl' \) \
      -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${FAKE_PREFIX_FOR_REPLACE}/..|g" {} \;
    
    find "${pkgdir}${_qt5_prefix}/lib/pkgconfig" -type f -name '*.pc' \
      -exec sed -i -e "s|${MINGW_PREFIX_WIN}|${MINGW_PREFIX}|g" {} \;
  fi
}

package_qt5-static() {
  package_it
}

package_qt5() {
  package_it
}

package_qt5-debug() {
  cp -rf ${srcdir}/${CARCH}-debug${MINGW_PREFIX} "${pkgdir}"/
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;

# 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=('3a530d1b243b5dec00bc54937455471aaa3e56849d2593edb8ded07228202240'
            '884b32f0e2e1bb110330a921b69443379a7be98c42f13754f9c5f56c040ba3b7'
            '617e6fa85a92353d0073425d37cd5d90d92cb7f906d66dd2d0df576122d091a4'
            '27ce2161b5dbea2fcce6b15948ab722a71036d056420854f6554969f683583bb'
            'e04033364f5ad77906b4100c34572df57bd793a55bc33b7d8a753a2cc60af259'
            '18fd2fa42215ac47b3b314261ab98cbe65f8231429e4f29a152288a3ca93daf1'
            '4e154fbc9059a096c351d019da6b18c907b1d8b06e028f48c7365f62bcd0edc9'
            'd99a4b74a062912a6913a883655d67257715866209a5c17cf9a3e6837dbd9260'
            '465d3897c4494695b66ac121944b3bd370db91bfea71dd2c9170dbf268cc99ea'
            '678c185795a41c7f38822120030585a0427287f3a1c2df9616daaa89f3285df3'
            'd8a476be7e55e8bb9362868073dc9e7937431e68b9578c0a0ed103cf1ebc8c01'
            'd7c228df3cc680793a6c858e1fac01092c0877071c075804b7e93f6b3a481eae'
            '97fcd6bd58ff8b8d735a6381b607bb3b4b351d1d07be1bbc18b97155dcbb501d'
            'f80ce415f25f0aa4ead2efe369b41efe35d9848d4d36d8dbf3831e48dbd6e506'
            '19566c38bd50581acaa6a9f46f0e25c41fdfc8b0b42269126e4d3a9b83e2f224'
            'ddaa067d144f5788ab7a3ed0dfc426d702c13de9c35f04eaaf38d642be4934d4'
            '8beeb610df3aff14bae43c56e5781cda3d49f1ad23c6e3fc2aa2405ce002de46'
            'f008164ef2a224b8c52736bab53f1aeec72d610928f03cce57f632824dfdd615'
            'a09ba083957a2b9020b5e17e57db98c3f41390db26d85b310798597fc2a4d34f'
            '42724bd154ed98c612d19a7daee2b5028270ef6dbfe7f35d5f97c8d0605f9fe6'
            '3dc4d7c4fed8fedd726211edbfe13f4d78247d3ab2f789f3ce2a8e43e59a7c5b'
            'c84cb5ba4243413232bc693fb0f54c0283bf0e496e6790a2698f226f80275a61'
            '69e1d6f8fc59ee2da0abe0a6965d0d7730bd015c5b1f1c5b4a69435328b21768'
            '00e32052ac1a9a8391275dfe69901d4ae146ac1441c00bf46f3ef1cfe459a78d'
            '8a74fab12c9d3faac81d75ea1c0662624b83059631db8d9f2570b414d62dc692'
            'b878680172290ad2dcb5508827ef5a9230cbfd8e97d2672d2e96b5addbd55833'
            '928a8eaca8840ff353cdff8fd11140724cb89094e6115fdd7b8cf534830adcca'
            'f07ff4f72626b91aa67ce7ffc78ce7c7c5765bf5431a65b7d867b5f66fa1506b'
            'f930338562119f542b550e3cdb802f1f7ebd476f54dd7297db424271167394b0'
            '28ad823dc8b6665de7b552e82411a8b7b25bf716c42597d8dc8644bded63199c'
            '9ea7aeb486023f3aebf1af44603ebd9266009aaeaf91e52c37c8c5154ea3900c'
            '7e57ce20b6707bc3b4a727da3287cadda13a74317d86515358b2535bc15244c7'
            '052c7035ad9a4fc0321975ba7658fb755bbc0841c7e1d9e88bb0a15e6a90b770'
            '157b97b3e3031d93d93e45368a1c54ebfbf9578116f75f5126e977e5dd518191'
            '502e61c1a1750f6bbc3aa7149e5e4c5ec96a1c5a91bee290771a35e172b45bb4')
