# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=creduce
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
replaces=("${MINGW_PACKAGE_PREFIX}-${_realname}-git")
pkgver=2.10.0.r110.g31e855e
pkgrel=2
_commit=31e855e290970cba0286e5032971509c0e7c0a80
pkgdesc="A C program reducer (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/csmith-project/creduce'
license=('spdx:NCSA')
depends=('perl-Benchmark-Timer'
         'perl-Exporter-Lite'
         'perl-File-Which'
         'perl-Getopt-Tabular'
         'perl-Regexp-Common'
         "${MINGW_PACKAGE_PREFIX}-astyle"
         "${MINGW_PACKAGE_PREFIX}-indent"
         "${MINGW_PACKAGE_PREFIX}-clang-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-clang"
             "git")
source=(${_realname}::git+https://github.com/csmith-project/creduce#commit=${_commit}
        "001-llvm19.patch"
        "002-llvm20.patch")
sha256sums=('94887099adcc2e98dc829fb2c00b587aa8693346951bfca7674fd9086925b9e8'
            '67fd2736c16699d4e0e35c13c247c4c59ee9c0ce7c3f75403956aec0ab0f04eb'
            '3ad5859c447ccbabee7da5818354ab91f11aeabc71948ff906eabbae508fe246')

pkgver() {
  cd "${srcdir}/${_realname}"
  git describe --long ${_commit} | sed 's/creduce-//g;s/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
}

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

prepare() {
  cd "${srcdir}/${_realname}"

  # https://github.com/csmith-project/creduce/issues/276
  apply_patch_with_msg \
    001-llvm19.patch

  apply_patch_with_msg \
    002-llvm20.patch
}

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

  ../${_realname}/configure \
      --prefix=${MINGW_PREFIX} \
      --build=${MINGW_CHOST} \
      --host=${MINGW_CHOST}

  make
}

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

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

  # Point creduce perl script:
  # #!/${MINGW_PREFIX} -> #!/usr
  # ..  to msys2 perl.
  sed "s|#!${MINGW_PREFIX}|#!/usr|g" \
    -i "${pkgdir}"${MINGW_PREFIX}/bin/creduce
}
