# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=oneTBB
pkgbase=mingw-w64-tbb
pkgname=("${MINGW_PACKAGE_PREFIX}-tbb")
pkgver=2022.2.0
pkgrel=1
pkgdesc='oneAPI Threading Building Blocks (mingw-w64)'
arch=(any)
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://software.intel.com/en-us/oneapi/onetbb'
msys2_repository_url="https://github.com/uxlfoundation/oneTBB"
msys2_references=(
  "cpe: cpe:2.3:a:intel:threading_building_blocks"
)
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-hwloc")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/uxlfoundation/oneTBB/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        001-fix-using-TBB-with-Debug-build-type.patch
        002-fix-link-flags-on-mingw.patch
        003-fix-getting-assembler-version-on-mingw.patch)
sha256sums=('f0f78001c8c8edb4bddc3d4c5ee7428d56ae313254158ad1eec49eced57f6a5b'
            '094c556a1087563a3a5810db0fa81aed6432b3a8e91aab9a747e9a55ea262f2a'
            '68e228b4cb2226192ac06d2b73eb4fe33c1ebae18e465d299d4f37da1ea3d9e7'
            'd51db2fc6acbb6022fe1e9b0188d0b5bc7041b9db0905cad8a58d6fde3d1750e')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd ${_realname}-${pkgver}
  apply_patch_with_msg \
    001-fix-using-TBB-with-Debug-build-type.patch \
    002-fix-link-flags-on-mingw.patch \
    003-fix-getting-assembler-version-on-mingw.patch

  find . -name "*.orig" -exec rm -f {} \;
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${CC} == gcc ]]; then
    _extra_config+=("-DTBB_ENABLE_IPO=OFF")
  else
    _extra_config+=("-DTBB_ENABLE_IPO=ON")
  fi

  CXXFLAGS+=" -D_WIN32_WINNT=0x0A00 -DNTDDI_VERSION=0x0A000002"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DTBB_TEST=OFF \
    -DTBB_STRICT=OFF \
    -DBUILD_SHARED_LIBS=ON \
    -S ${_realname}-${pkgver} \
    -B build-${MSYSTEM}

  ${MINGW_PREFIX}/bin/cmake --build build-${MSYSTEM}
}

package() {
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install build-${MSYSTEM}
  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/LICENSE.txt \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
