# Maintainer: Marian Buschsieweke <marian.buschsieweke@posteo.net>

_targets="
	arm-none-eabi
	riscv-none-elf
	"
pkgname=picolibc
pkgver=1.8.6
_gccver=14.2.0
pkgrel=2
pkgdesc="A C standard library based on newlib with focus on compact size"
url="https://github.com/picolibc/picolibc"
makedepends="meson"
# limited by newlib
arch="aarch64 ppc64le x86_64 x86"
license="GPL-2.0-only AND LGPL-2.1-only AND 0BSD AND BSD-3-Clause AND GPL-3.0-only AND LGPL-3.0-only"
source="$pkgname-$pkgver.tar.xz::https://github.com/picolibc/picolibc/releases/download/$pkgver/picolibc-$pkgver.tar.xz"
options="!check"

for target in $_targets; do
	subpackages="picolibc-$target:_install_subpkg $subpackages"
	makedepends="binutils-$target gcc-$target~$_gccver newlib-$target $makedepends"
done

prepare() {
	default_prepare

	# Handle mismatch of target triples
	mv "$builddir/scripts/cross-riscv64-unknown-elf.txt" \
		"$builddir/scripts/cross-riscv-none-elf.txt"
	sed -e 's/riscv64-unknown-elf/riscv-none-elf/g' \
		-i "$builddir/scripts/cross-riscv-none-elf.txt"
}

build() {
	for target in $_targets; do
		# CFLAGS and LDFLAGS from the host (Linux) do not necessarily make sense
		# for the target (bare metal MCU)
		unset CFLAGS
		unset LDFLAGS
		# cannot use abuild-meson here, as target != host
		meson \
			--prefix=/usr/ \
			--buildtype=plain \
			--cross-file=scripts/cross-$target.txt \
			-Dincludedir=picolibc/$target/include \
			-Dlibdir=picolibc/$target/lib \
			. build-$target
		meson compile -C build-$target
	done
}

package() {
	for target in $_targets; do
		depends="$depends picolibc-$target"
	done
	mkdir -p "$pkgdir"
}

_install_subpkg() {
	target="${subpkgname#picolibc-}"
	pkgdesc="A C standard library based on newlib with focus on compact size for $target"
	depends="binutils-$target gcc-$target~$_gccver $depends"

	DESTDIR="$subpkgdir" meson install -C "$builddir/build-$target"
}

sha512sums="
f7e03aed7f24fb7a52f1e44bc244abccb72159b01c591aa68c43499f320765a559e4cdfd996bec855447781d8db311bc34f111a4d233cfdaa783f8347bf03f09  picolibc-1.8.6.tar.xz
"
