# Maintainer: Manuel Naranjo <naranjo.manuel@gmail.com>

_pyname=psutil
_realname=${_pyname}
pkgbase=mingw-w64-python-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-python-${_realname}")
pkgver=7.0.0
pkgrel=1
pkgdesc="A cross-platform process and system utilities module for Python (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/giampaolo/psutil"
msys2_references=(
  'purl: pkg:pypi/psutil'
  "cpe: cpe:2.3:a:psutil_project:psutil"
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-python")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-build"
             "${MINGW_PACKAGE_PREFIX}-python-installer"
             "${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-cc")
checkdepends=("${MINGW_PACKAGE_PREFIX}-python-pytest"
              "${MINGW_PACKAGE_PREFIX}-python-pywin32"
              "${MINGW_PACKAGE_PREFIX}-python-wmi")
source=("https://pypi.org/packages/source/${_realname::1}/${_realname}/${_realname}-${pkgver}.tar.gz"
        "0001-mingw-fixes-without-loadlib.patch"
        "0002-pyparsepid.patch"
        "0003-avoid-duplicate-symbols.patch")
sha256sums=('7be9c3eba38beccb6495ea33afd982a44074b78f28c434a1f51cc07fd315c456'
            'df8e02d1970d5f9b7df84ae9ad1ba4f86ae069ffce444ae64801b21f66e37bba'
            '6b1bbe9116612ac980490cea6d2de01e0f1ef44cd6289386d28c0f5f12d8f5b7'
            'd877059c372f9d449dafd9781434d329e28f32fa88d11bd1ec11de30b34a9999')

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

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}
  apply_patch_with_msg \
    0001-mingw-fixes-without-loadlib.patch

  # https://github.com/msys2/MINGW-packages/issues/18460#issuecomment-1717951357
  # CPython defines it as int, so we do as well
  apply_patch_with_msg \
    0002-pyparsepid.patch

  apply_patch_with_msg \
    0003-avoid-duplicate-symbols.patch

  cd "${srcdir}"
  rm -rf python-build-${MSYSTEM} | true
  cp -r "${_realname}-${pkgver}" "python-build-${MSYSTEM}"
}

build() {
  cd "${srcdir}/python-build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/python -m build --wheel --skip-dependency-check --no-isolation
}

check() {
  cd "${srcdir}/python-build-${MSYSTEM}"
  _platform=$(python -c "import sysconfig; print(sysconfig.get_platform())")
  _soabi=$(python -c "import sysconfig; print(sysconfig.get_config_var('SOABI'))")
  cd build/lib.${_platform}-${_soabi}
  ${MINGW_PREFIX}/bin/python -m pytest || warning "Tests failed"
}

package() {
  cd "${srcdir}/python-build-${MSYSTEM}"
  MSYS2_ARG_CONV_EXCL="--prefix=" \
    ${MINGW_PREFIX}/bin/python -m installer --prefix=${MINGW_PREFIX} \
    --destdir="${pkgdir}" dist/*.whl

  install -Dm644 LICENSE "${pkgdir}${MINGW_PREFIX}/share/licenses/python-${_realname}/COPYING"
}
