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

_realname=jemalloc
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=5.3.0
pkgrel=1
pkgdesc="General-purpose scalable concurrent malloc implementation (mingw64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="http://jemalloc.net/"
license=('BSD')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-docbook-xsl")
source=("https://github.com/jemalloc/jemalloc/releases/download/${pkgver}/${_realname}-${pkgver}.tar.bz2"
        001-fix-library-extension.patch
        002-makefile.patch)
sha256sums=('2db82d1e7119df3e71b7640219b6dfe84789bc0537983c3b7ac4f7189aecfeaa'
            '74569f3e709855f53b83212efa7641b1b4b4f84442ba8c0729813bc214f18230'
            '0c5112b89244eeb781cd321584aa50f89808cccf03060d640cdf891eb4a270b5')

# Helper macros to help make tasks easier #
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 \
    001-fix-library-extension.patch \
    002-makefile.patch
}

build() {
  declare -a _btype
  if check_option "debug" "y"; then
    _btype="--enable-debug --enable-log"
  else
    _btype=
  fi

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

  CFLAGS+=" -std=gnu11"
  _XMLROOT=$(ls -d ${MINGW_PREFIX}/share/xml/docbook/xsl-stylesheets* | tail -n1)
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --enable-autogen \
    --with-xslroot=${_XMLROOT} \
    ${_btype}

  make
}

check() {
  cd "${srcdir}"/build-${MSYSTEM}
  make check || true
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  make DESTDIR="${pkgdir}" install

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