# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=itstool
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.7
pkgrel=3
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
pkgdesc="XML to PO and back again (mingw-w64)"
url="https://itstool.org/"
msys2_repository_url='https://github.com/itstool/itstool'
license=("spdx:GPL-3.0-or-later")
depends=("${MINGW_PACKAGE_PREFIX}-python"
         "${MINGW_PACKAGE_PREFIX}-python-lxml")
makedepends=("${MINGW_PACKAGE_PREFIX}-python-setuptools"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-cc")
options=('!strip')
source=("https://files.itstool.org/itstool/${_realname}-${pkgver}.tar.bz2"
        https://github.com/itstool/itstool/commit/32c7d07664dc37765100285d1202d488cd6a27e8.patch
        57.patch
        'reloc.patch'
        'pyscript2exe.py')
sha256sums=('6b9a7cd29a12bb95598f5750e8763cee78836a1a207f85b74d8b3275b27e87ca'
            '4e64a2e884f9d4cbc493732fcbde9f1d5bed534f9a66330bbcc1cbeb54808c1e'
            'ad89a36fd36b985daeec87003c9cc8c98abee3f2de84644aa10241b2d22098cf'
            'f292bcd116da4ea36ee9c42e206dbd9151d147da1ef5a078e743fc9ed0a4ab47'
            '3c65bc3dd7337877e14b19bc7c42918bde664a11a860cfc0b9db891f8a1052db')

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

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

  _apply_patch_with_msg \
    32c7d07664dc37765100285d1202d488cd6a27e8.patch \
    reloc.patch

  # https://github.com/itstool/itstool/pull/57 - squashed without tests
  _apply_patch_with_msg 57.patch


  autoreconf -fvi
}

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

  PYTHON="${MINGW_PREFIX}/bin/python3" \
    ../${_realname}-${pkgver}/configure \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --build=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX}

  make
}

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

  make check
}

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

  make DESTDIR="${pkgdir}" install

  ${MINGW_PREFIX}/bin/python "${srcdir}/pyscript2exe.py" "${pkgdir}${MINGW_PREFIX}/bin/itstool"
  local _PRE_WIN="$(cygpath -m ${MINGW_PREFIX})"
  sed -e "s|${_PRE_WIN}|${MINGW_PREFIX}|g" \
    -i "${pkgdir}${MINGW_PREFIX}"/bin/itstool-script.py
}
