# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=intel-tbb
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2020.2
pkgrel=2
epoch=1
pkgdesc='High level abstract threading library (mingw-w64)'
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-make")
options=('!strip' 'staticlibs')
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
url='https://www.threadingbuildingblocks.org/'
license=('Apache')
source=(${_realname}-${pkgver}.tar.gz::https://github.com/intel/tbb/archive/v${pkgver}.tar.gz
        "tbb-cmake-config.patch")
sha256sums=('4804320e1e6cbe3a5421997b52199e3c1a3829b2ecb6489641da4b8e32faf500'
            'f5aa6bb43a69a46a0cec4d2b3e84e7e6e102b3becd1b58d496e8ee035829dc85')

prepare () {
  cd ${srcdir}/oneTBB-${pkgver}
  patch -p1 -i ${srcdir}/tbb-cmake-config.patch
}

build() {
  cd ${srcdir}/oneTBB-${pkgver}

  sed -i "s|OUTPUT_KEY = -o #|OUTPUT_KEY = -Wl,--out-implib,lib\$(BUILDING_LIBRARY).a -o #|g" build/windows.gcc.inc
  echo "CPLUS_FLAGS += -mrtm" >> build/windows.gcc.inc # makes test cases pass

  if test "${MINGW_CHOST}" = "x86_64-w64-mingw32"
  then
    parch=intel64
  else
    parch=ia32
  fi
  unset LDFLAGS
  mingw32-make arch=${parch} tbb_os=windows runtime=mingw compiler=gcc stdver=c++11
  
  mkdir build-cmake && cd build-cmake
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"MSYS Makefiles" \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DINSTALL_DIR=${srcdir}/oneTBB-${pkgver}/build-cmake \
    -DSYSTEM_NAME=Windows \
    -DTBB_VERSION_FILE=${srcdir}/oneTBB-${pkgver}/include/tbb/tbb_stddef.h \
    -DINC_REL_PATH=../../../include \
    -DLIB_REL_PATH=../../../lib \
    -DBIN_REL_PATH=../../../bin \
    -P ${srcdir}/oneTBB-${pkgver}/cmake/tbb_config_installer.cmake
}

package() {
  cd ${srcdir}/oneTBB-${pkgver}

  if test "${MINGW_CHOST}" = "x86_64-w64-mingw32"
  then
    parch=intel64
  else
    parch=ia32
  fi

  install -d "${pkgdir}${MINGW_PREFIX}"/include
  cp -a include/tbb "${pkgdir}${MINGW_PREFIX}"/include
  install -d "${pkgdir}${MINGW_PREFIX}"/bin
  #install -m755 build/windows_${parch}_gcc_mingw_debug/*.dll "${pkgdir}${MINGW_PREFIX}"/bin
  install -m755 build/windows_${parch}_gcc_mingw_release/*.dll "${pkgdir}${MINGW_PREFIX}"/bin
  install -d "${pkgdir}${MINGW_PREFIX}"/lib
  #install -m755 build/windows_${parch}_gcc_mingw_debug/*.a "${pkgdir}${MINGW_PREFIX}"/lib
  install -m755 build/windows_${parch}_gcc_mingw_release/*.a "${pkgdir}${MINGW_PREFIX}"/lib
  
  # Install cmake files
  install -d "${pkgdir}${MINGW_PREFIX}"/lib/cmake/tbb
  install -m644 build-cmake/TBBConfig.cmake "${pkgdir}${MINGW_PREFIX}"/lib/cmake/tbb/
  install -m644 build-cmake/TBBConfigVersion.cmake "${pkgdir}${MINGW_PREFIX}"/lib/cmake/tbb/
}
