### CachyOS PKGBUILD Maintainers:
# Maintainer: Eric Naim <dnaim@cachyos.org>
# Maintainer: Peter Jung <admin@ptr1337.dev>


pkgname=(
  lib32-zlib-ng
  lib32-zlib-ng-compat
)
pkgver=2.3.3
pkgrel=2
pkgdesc='zlib replacement with optimizations for next generation systems - 32-bit'
url='https://github.com/zlib-ng/zlib-ng'
arch=('x86_64')
license=('custom:zlib')
depends=(
  lib32-glibc
)
makedepends=(
  git
  cmake
  ninja
  lib32-gcc-libs
)
source=(git+https://github.com/zlib-ng/zlib-ng#tag=${pkgver})
sha256sums=('aa625dc5ecdeb0ea6c12d76518dd10a55e865499c5a0fced68f52cb751542041')
b2sums=('9380c04753e0eab0b3fb5a72b115a65f5841fccb03f7e711e4bf5ed78888b3bb19085ade58b47c229868774333d20cd29301ae4f0e7db8c2d40414dfe6e71af2')


build() {
  cd "zlib-ng"


  ## Build for 32-bit
  export CFLAGS+=" -m32 -fno-semantic-interposition"
  export CXXFLAGS+=" -m32 -fno-semantic-interposition"
  export LDFLAGS+=" -m32"
  export PKG_CONFIG_PATH='/usr/lib32/pkgconfig'

  # WITH_UNALIGNED - unaligned access invokes undefined behaviour,
  #   see https://github.com/gentoo/gentoo/pull/17167 for more info.
  local _options=(
    -G Ninja
    -DCMAKE_BUILD_TYPE=None
    -DCMAKE_INSTALL_PREFIX=/usr
    -DCMAKE_INSTALL_LIBDIR=lib32
    -Wno-dev
    -DWITH_GTEST=OFF
    -DBUILD_SHARED_LIBS=ON
  )

  echo "Building zlib-ng"
  cmake -B build \
    "${_options[@]}"
  cmake --build build

  echo "Building zlib-ng-compat"
  cmake -B build-compat \
    "${_options[@]}" \
    -DZLIB_COMPAT=ON
  cmake --build build-compat
}

check() {
  cd "zlib-ng"
  echo "Checking zlib-ng"
  ctest --output-on-failure --test-dir build
  echo "Checking zlib-ng-compat"
  ctest --output-on-failure --test-dir build-compat
}

package_lib32-zlib-ng() {
  provides=('libz-ng.so')
  depends=(zlib-ng)

  cd "zlib-ng"
  DESTDIR="${pkgdir}" cmake --install build
  install -Dm 644 LICENSE.md -t "${pkgdir}/usr/share/licenses/${pkgname}"
  install -Dm 644 README.md -t "${pkgdir}/usr/share/doc/${pkgname}"

  rm -rf "$pkgdir"/usr/include
}

package_lib32-zlib-ng-compat() {
  pkgdesc+=" (zlib compat)"
  provides=('lib32-zlib' 'libz.so')
  depends=(zlib-ng-compat lib32-zlib-ng)
  conflicts=('lib32-zlib')
  replaces=('lib32-zlib')
  options=('staticlibs')

  cd "zlib-ng"
  DESTDIR="${pkgdir}" cmake --install build-compat
  install -Dm 644 LICENSE.md -t "${pkgdir}/usr/share/licenses/${pkgname}"
  install -Dm 644 README.md -t "${pkgdir}/usr/share/doc/${pkgname}"

  rm -rf "$pkgdir"/usr/include
}

# vim: ts=2 sw=2 et:
