# Contributor: prspkt <prspkt@protonmail.com>
# Maintainer: prspkt <prspkt@protonmail.com>
pkgname=brotli
pkgver=1.1.0
pkgrel=2
pkgdesc="Generic lossless compressor"
url="https://github.com/google/brotli"
arch="all"
license="MIT"
depends_dev="$pkgname=$pkgver-r$pkgrel"
makedepends_build="cmake samurai"
subpackages="
	$pkgname-doc
	$pkgname-static
	$pkgname-dev
	$pkgname-libs
	"
if [ -z "$BOOTSTRAP" ]; then
	makedepends_host="python3-dev py3-gpep517 py3-setuptools py3-wheel"
	subpackages="$subpackages py3-$pkgname-pyc py3-$pkgname:py3"
fi
source="$pkgname-$pkgver.tar.gz::https://github.com/google/brotli/archive/refs/tags/v$pkgver.tar.gz
	optimize-mips-s390x.patch
	"

# secfixes:
#   1.0.9-r0:
#     - CVE-2020-8927

prepare() {
	default_prepare
	sed -i 's,/usr/bin/env bash,/bin/sh,' tests/*.sh
}

build() {
	# -flto=auto does not work when cross-compiling
	if [ "$CBUILD"  != "$CHOST" ]; then
		export CFLAGS="$CFLAGS -O2"
	else
		export CFLAGS="$CFLAGS -flto=auto -O2"
	fi

	# static libs, see https://github.com/google/brotli/issues/795
	cmake -B build -G Ninja \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DBUILD_SHARED_LIBS=OFF
	cmake --build build

	cmake -B build -G Ninja \
		-DCMAKE_BUILD_TYPE=None \
		-DCMAKE_INSTALL_PREFIX=/usr \
		-DBUILD_SHARED_LIBS=ON
	cmake --build build

	if [ -z "$BOOTSTRAP" ]; then
		gpep517 build-wheel \
			--wheel-dir .dist \
			--output-fd 3 3>&1 >&2
	fi
}

check() {
	ctest --output-on-failure --test-dir build

	python3 -m venv --clear --without-pip --system-site-packages .testenv
	.testenv/bin/python3 -m installer .dist/*.whl
	cd python; ../.testenv/bin/python3 -m unittest discover -v -p '*_test.py'
}

package() {
	DESTDIR="$pkgdir" cmake --install build

	local file; for file in common dec enc; do
		install -D -m 755 "$builddir"/build/libbrotli$file.a \
			"$pkgdir"/usr/lib/
	done

	local man; for man in docs/*.?; do
		install -D -m644 $man "$pkgdir"/usr/share/man/man${man##*.}/${man##*/}
	done

	if [ -z "$BOOTSTRAP" ]; then
		python3 -m installer -d "$pkgdir" .dist/*.whl
	fi
}

py3() {
	pkgdesc="$pkgdesc (python bindings)"

	amove usr/lib/python3*
}

sha512sums="
6eb280d10d8e1b43d22d00fa535435923c22ce8448709419d676ff47d4a644102ea04f488fc65a179c6c09fee12380992e9335bad8dfebd5d1f20908d10849d9  brotli-1.1.0.tar.gz
3f91155c76c27268b94515087d042b6669f790027cb394c694ec492bf2d5a9a98272fc501d179b4b3736a8be3e016189d2d996ee50ae3e07b52f21857cbfc391  optimize-mips-s390x.patch
"
