# Maintainer: Maksim Bondarenkov <maksapple2306@gmail.com>
# Contributor: Raed Rizqie <raed.rizqie@gmail.com>

_realname=maturin
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}"
         "${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.10.2
pkgrel=1
pkgdesc='Build and publish crates with pyo3, rust-cpython and cffi bindings (mingw-w64)'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://www.maturin.rs/'
msys2_repository_url='https://github.com/pyo3/maturin'
msys2_references=(
  'purl: pkg:pypi/maturin'
)
license=('spdx:MIT OR Apache-2.0')
makedepends=(
    "${MINGW_PACKAGE_PREFIX}-python-build"
    "${MINGW_PACKAGE_PREFIX}-python-installer"
    "${MINGW_PACKAGE_PREFIX}-python-setuptools-rust")
options=('!strip')
source=("https://pypi.org/packages/source/${_realname::1}/${_realname}/${_realname}-${pkgver}.tar.gz")
sha256sums=('259292563da89850bf8f7d37aa4ddba22905214c1e180b1c8f55505dfd8c0e81')

prepare() {
  cp -r "${_realname}-${pkgver}" "python-build-${MSYSTEM}" && cd "python-build-${MSYSTEM}"

  cargo fetch --locked --target "${RUST_CHOST}"
}

build() {
  cd "python-build-${MSYSTEM}"

  export MATURIN_SETUP_ARGS="--features full,rustls"
  python -m build --wheel --skip-dependency-check --no-isolation
}

package_python-maturin() {
  pkgdesc+=' (Python bindings)'
  depends=("${MINGW_PACKAGE_PREFIX}-python" "${MINGW_PACKAGE_PREFIX}-maturin")

  cd "python-build-${MSYSTEM}"

  MSYS2_ARG_CONV_EXCL="--prefix=" \
    python -m installer --prefix=${MINGW_PREFIX} \
    --destdir="${pkgdir}" dist/*.whl

  install -Dm644 license-{apache,mit} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/"

  # split maturin executable
  mkdir -p "dest${MINGW_PREFIX}/bin"
  mv "${pkgdir}${MINGW_PREFIX}"/bin/* "dest${MINGW_PREFIX}/bin/"
}

package_maturin() {
  cd "python-build-${MSYSTEM}"

  mv dest/* "${pkgdir}"

  local _complete="${pkgdir}${MINGW_PREFIX}/bin/maturin completions"
  $_complete bash | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/bash-completion/completions/maturin"
  $_complete zsh | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/zsh/site-functions/_maturin"
  $_complete fish | install -Dm644 /dev/stdin "${pkgdir}${MINGW_PREFIX}/share/fish/vendor_completions.d/maturin.fish"
  install -Dm644 license-{apache,mit} -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/"
}

# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
