# Maintainer: Yang Kun <ikspress@outlook.com>

_realname=judy
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.0.5
pkgrel=1
pkgdesc='C library for creating and accessing dynamic arrays'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
license=('spdx:LGPL-2.1-or-later')
makedepends=("${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-cc")
url='http://judy.sourceforge.net'
source=("https://downloads.sourceforge.net/judy/Judy-${pkgver}.tar.gz"
        "0001-judy-no-undefined.patch"
        # https://sources.debian.org/patches/judy/latest/
        "https://sources.debian.org/data/main/j/judy/1.0.5-5.1/debian/patches/04_fix_undefined_bahavior_during_aggressive_loop_optimizations.patch"
        # https://sourceforge.net/p/judy/patches/6/
        "https://sourceforge.net/p/judy/patches/6/attachment/0001-automake-Makefile.am-use-relocatable-srcdir-when-app.patch"
        "https://sourceforge.net/p/judy/patches/6/attachment/0002-doc-Makefile.am-mkdir-p-man-man3-and-parallel-buildi.patch"
        "https://sourceforge.net/p/judy/patches/6/attachment/0003-Win64-Fixup-WORD_T-and-UL-suffixes-for-llp64-data-mo.patch")
sha256sums=('d2704089f85fdb6f2cd7e77be21170ced4b4375c03ef1ad4cf1075bd414a63eb'
            '4ab00dee64c79c3296ae7bc12429411bf7e361aedd583f268c0ad40c2083080e'
            'e70bab80362bb72f93f39d684b496a2dadb46f8da2469b76a9d5d2a064fd7274'
            '96e0ad7536f45e9bbbf2f6e9f6de12f74f1a9c349fcbd0d44db52b3c1231140a'
            '73da528014ee64b239d5db2aaf3d69682424e9cf6318dbc034e2e52e05deecff'
            '30dfe143bda003cbcfe90d90328f8caf8122406145d7c03f3c1b19620a11359f')

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

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

  apply_patch_with_msg 0001-judy-no-undefined.patch

  # Apply patches from Debian
  apply_patch_with_msg \
    04_fix_undefined_bahavior_during_aggressive_loop_optimizations.patch

  # Apply patches from SourceForge
  apply_patch_with_msg \
    0001-automake-Makefile.am-use-relocatable-srcdir-when-app.patch \
    0002-doc-Makefile.am-mkdir-p-man-man3-and-parallel-buildi.patch \
    0003-Win64-Fixup-WORD_T-and-UL-suffixes-for-llp64-data-mo.patch

  autoreconf -fi
}

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

  mkdir -p "doc/man/man3"

  ../Judy-${pkgver}/configure \
    --prefix="${MINGW_PREFIX}" \
    --build="${MINGW_CHOST}" \
    --host="${MINGW_CHOST}" \
    --target="${MINGW_CHOST}"

  make
}

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

  make install DESTDIR="${pkgdir}"

  # Add section number to file extension
  for file in "${pkgdir}${MINGW_PREFIX}/share/man/man3/"*; do
    mv "${file}" "${file%.*}.3"
  done

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