# Maintainer: Leonardo Arena <rnalrd@alpinelinux.org>

# rtpengine version
# when changing _ver we *must* bump _rel
_ver=12.1.1.4
_rel=0

# kernel version
# when changing _kver make sure _krel=0 & _rel=0
_kver=6.6.51
_krel=0

_kpkgver="$_kver-r$_krel"

# for custom kernels set $FLAVOR
_extra_flavors=
if [ -z "$FLAVOR" ]; then
	_flavor=lts
	case $CARCH in
	x86|x86_64|armv7|aarch64) _extra_flavors="virt";;
	esac
else
	_flavor=$FLAVOR
fi
_kpkg=linux-$_flavor

pkgname=rtpengine-$_flavor
pkgver=$_kver
pkgrel=$((_rel + _krel))

pkgdesc="Kernel module for rtpengine"
url="https://github.com/sipwise/rtpengine"
# armhf and riscv64 blocked by linux-lts
arch="all !armhf !riscv64"
license="GPL-3.0-only"
makedepends="linux-$_flavor-dev=$_kpkgver"
install_if="rtpengine linux-$_flavor=$_kpkgver"
options="!check"
source="$pkgname-$_ver.tar.gz::https://github.com/sipwise/rtpengine/archive/mr$_ver.tar.gz"
builddir="$srcdir"/rtpengine-mr$_ver

for f in $_extra_flavors; do
	makedepends="$makedepends linux-$f-dev=$_kpkgver"
	subpackages="$subpackages rtpengine-$f:_extra"
done

prepare() {
	default_prepare
	if [ -z "$FLAVOR" ]; then
		( . "$startdir"/../../main/linux-"$_flavor"/APKBUILD
			[ "$_kver" != "$pkgver" ] && die "please update _kver to $pkgver"
			[ "$_krel" != "$pkgrel" ] && die "please update _krel to $pkgrel"
			return 0
		)
	fi
	local flavor=
	for flavor in $_flavor $_extra_flavors; do
		cp -r "$builddir" "$srcdir/$flavor"
	done
}

build() {
	unset LDFLAGS
	local flavor= kabi=
	for flavor in $_flavor $_extra_flavors; do
		kabi="$_kver-$_krel-$flavor"
		make -C "$srcdir/$flavor"/kernel-module \
			KSRC=/lib/modules/"$kabi"/build
	done
}

package() {
	local kabi="$_kver-$_krel-$_flavor"
	install -Dm644 "$srcdir/$_flavor"/kernel-module/xt_RTPENGINE.ko \
		"$pkgdir/lib/modules/$kabi/extra/xt_RTPENGINE.ko"
}

_extra() {
	flavor=${subpkgname##*-}
	# shellcheck disable=SC2154
	depends="linux-$flavor=$_kpkgver"
	install_if="rtpengine linux-$flavor=$_kpkgver"
	pkgdesc="$flavor kernel modules for rtpengine"
	local kabi="$_kver-$_krel-$flavor"
	install -Dm644 "$srcdir"/virt/kernel-module/xt_RTPENGINE.ko \
		"$subpkgdir/lib/modules/$kabi/extra/xt_RTPENGINE.ko"
}

sha512sums="
f3b9987ca253f52e6c2f6c5de7c06b579a002a6bb92314a71d4fb21542ee9d34332bf2e3b600875479a3e34276f0eea8ad1ba5fabed6464f2bc3f57db6f3a5cf  rtpengine-lts-12.1.1.4.tar.gz
"
