# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=readstat
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.1.9
pkgrel=1
pkgdesc="Command-line tool (+ C library) for converting SAS, Stata, and SPSS files. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://github.com/WizardMac/ReadStat'
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-libiconv"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-cc")
source=("https://github.com/WizardMac/ReadStat/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-use-after-free.patch::https://github.com/WizardMac/ReadStat/commit/718d4915.patch"
        "002-remove-Wstrict-prototypes-warnings.patch::https://github.com/WizardMac/ReadStat/commit/211c342a.patch"
        "003-fix-build-on-ucrt.patch")
sha256sums=('89af7c785a7ae3d9a7af6e64a69028829a429f66a14b1b913be22816dc07ddca'
            '6484e47db3e2077b5db9d92bd0218678ae0389152a5f7b50ed7cd0ba4b0a6b50'
            'cc77c789a5d63bf85ac24a6fd2f0ffed027a17addc3acf2661dd014f09b88d36'
            'a6a4f5e3df90a4e5ff42cc9bf71d474f0214558d697af79ea0198cc75094cb7b')

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

prepare() {
  cd "ReadStat-${pkgver}"

  apply_patch_with_msg \
    001-fix-use-after-free.patch \
    002-remove-Wstrict-prototypes-warnings.patch \
    003-fix-build-on-ucrt.patch

  sed -i "s|-Werror||g" Makefile.am

  autoreconf -fiv
}

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

  ../"ReadStat-${pkgver}"/configure \
    --prefix="${MINGW_PREFIX}" \
    --enable-shared

  make
}

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

  make install DESTDIR="${pkgdir}"

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