# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>
# Contributor: dragon-archer <dragon-archer@outlook.com>

_realname=oneTBB
pkgbase=mingw-w64-tbb
pkgname=("${MINGW_PACKAGE_PREFIX}-tbb")
pkgver=2023.0.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
        003-fix-getting-assembler-version-on-mingw.patch
        004-link-test-with-wintrust.patch)
sha256sums=('f8767b971ec6aea25dde58ae0f593e94e7aa75a739a86f67967012f69e2199b1'
            '094c556a1087563a3a5810db0fa81aed6432b3a8e91aab9a747e9a55ea262f2a'
            'af32506f50a41623999f39835e84b24c8eb78f866a31a5305195bbce47185e6c'
            'dca2c65246a71c072048b3156732aa54d753397a9b8b3f8a5fb11242eb12179b')

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 \
    003-fix-getting-assembler-version-on-mingw.patch \
    004-link-test-with-wintrust.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 [[ ${MSYSTEM} == MINGW* ]]; then
    CXXFLAGS+=" -D_WIN32_WINNT=0x0A00 -DNTDDI_VERSION=0x0A000002"
  fi

  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}
}

check() {
  ${MINGW_PREFIX}/bin/cmake -DTBB_TEST=ON -S ${_realname}-${pkgver} -B build-${MSYSTEM}
  ${MINGW_PREFIX}/bin/cmake --build build-${MSYSTEM}
  # 7 tests failed out of 141
  ${MINGW_PREFIX}/bin/ctest --test-dir build-${MSYSTEM} --output-on-failure || true
}

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