# Maintainer: https://github.com/bustercopley

_realname=libunifex
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=r692.fdd2c23
pkgrel=1
pkgdesc='A prototype implementation of the C++ sender/receiver async programming model (mingw-w64)'
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
license=('spdx:Apache-2.0')
url="https://github.com/facebookexperimental/libunifex"
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             'git')
_commit='fdd2c23'
source=("${_realname}::git+https://github.com/facebookexperimental/${_realname}.git#commit=${_commit}"
        "001-missing-memset.patch")
sha256sums=('SKIP'
            'f9375ed32056557795834b57f7d65929ecdcaced9cefaf763eca7bb8fe89e53c')

pkgver() {
  cd "${srcdir}/${_realname}"
  printf "r%s.%s" "$(git rev-list --count "${_commit}")" "$(git rev-parse --short "${_commit}")"
}

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

prepare() {
  cd "${srcdir}/${_realname}"
  sed -i "s/-Werror//g" cmake/unifex_env.cmake

  apply_patch_with_msg \
    001-missing-memset.patch
}

build(){
  mkdir -p "${srcdir}/build-${MSYSTEM}"
  cd "${srcdir}/build-${MSYSTEM}"

  if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
      CXX_FLAGS="-stdlib=libc++"
  else
      CXX_FLAGS="-fcoroutines"
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_CXX_FLAGS:STRING="${CXX_FLAGS}" \
    -DCMAKE_CXX_STANDARD:STRING=20 \
    -DCMAKE_BUILD_TYPE=Release \
    ../${_realname}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  install -Dm644 "${srcdir}/${_realname}/LICENSE.txt" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.txt"
}
