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

_realname=manifold
pkgbase=mingw-w64-${_realname}
pkgname=(${MINGW_PACKAGE_PREFIX}-${_realname})
provides=(${MINGW_PACKAGE_PREFIX}-${_realname}-git)
conflicts=(${MINGW_PACKAGE_PREFIX}-${_realname}-git)
replaces=(${MINGW_PACKAGE_PREFIX}-${_realname}-git)
pkgver=3.2.1
pkgrel=1
pkgdesc="Geometry library for topological robustness (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/elalish/manifold"
license=('Apache-2.0')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-nanobind"
             "${MINGW_PACKAGE_PREFIX}-pybind11"
             "${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-tbb"
             'git')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-clipper2"
         "${MINGW_PACKAGE_PREFIX}-python")
source=("https://github.com/elalish/manifold/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        0001-build-mingw.patch)
sha256sums=('67c4e0cb836f9d6dfcb7169e9d19a7bb922c4d4bfa1a9de9ecbc5d414018d6ad'
            '84fd0bd9193d2051d72db3e33c4a215d2cabe0b5c788e2790b23c12f0a1f7dd8')

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 \
    0001-build-mingw.patch
}

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

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi
  
  local _pysite=$(cygpath -u $(${MINGW_PREFIX}/bin/python -c "import sysconfig; print(sysconfig.get_path('platlib'))"))

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=;-DPY_SITEARCH=" \
    ${MINGW_PREFIX}/bin/cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DMANIFOLD_PYBIND=ON \
      -DMANIFOLD_PAR=ON \
      -DPYTHON_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
      -DPython_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
      -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
      -DPython3_ROOT_DIR=${MINGW_PREFIX} \
      -DPython3_FIND_REGISTRY=NEVER \
      -DPY_SITEARCH=${_pysite} \
      ../${_realname}-${pkgver}

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

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

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

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