# Kernel config based on defconfig and exynos7870.config
maintainer="methanal <kauschluss+methanal@disroot.org>"
pkgname=linux-postmarketos-exynos7870
pkgver=6.15
pkgrel=6
pkgdesc="Close-to-mainline kernel for Samsung Exynos 7870 devices"
arch="aarch64"
_carch="arm64"
_flavor="postmarketos-exynos7870"
url="https://gitlab.com/exynos7870-mainline/linux"
license="GPL-2.0-only"
options="!strip !check !tracedeps pmb:cross-native"
makedepends="
	bc
	bison
	clang
	elfutils-dev
	flex
	linux-headers
	lld
	llvm
	openssl-dev
	pahole
	perl
	postmarketos-installkernel
	python3
	zstd
"

_owner="exynos7870-mainline"
_repo="mainline-patches"
_commit="5686e3b545bd34e80ec6e73604b8819d10e52a2c"
_config="config-$_flavor.aarch64"
_kmajver="$(echo "$pkgver" | sed 's/\..*$//')"

# Source
source="
	linux-$pkgver.tar.gz::https://cdn.kernel.org/pub/linux/kernel/v$_kmajver.x/linux-$pkgver.tar.gz
	patches-$_commit.tar.gz::https://gitlab.com/$_owner/$_repo/-/archive/$_commit/$_repo-$_commit.tar.gz
	$_config
"
builddir="$srcdir/linux-$pkgver"

prepare() {
	default_prepare
	cp "$srcdir/$_config" .config

	# Apply the patches to the mainline kernel.
	for patchfile in "$srcdir/$_repo"-*/patches/*; do
		patch -p1 < "$patchfile"
	done

	makefile="$builddir/arch/arm64/boot/dts/exynos/Makefile"

	for dts in "$srcdir/$_repo"-*/devicetrees/*dts*; do
		dtb="$(basename "$dts" | sed 's/\.dts$/.dtb/')"

		# Move the devicetree sources in the kernel tree.
		cp "$dts" "arch/arm64/boot/dts/exynos/"

		# Mention the devicetree blobs in the Makefile for
		# compilation if they're absent.
		if ! grep -q "$dtb" "$makefile"; then
			echo "dtb-\$(CONFIG_ARCH_EXYNOS) += $dtb" >> "$makefile"
		fi
	done
}

build() {
	unset LDFLAGS
	make ARCH="$_carch" LLVM=1 HOSTLDFLAGS="-fuse-ld=lld" \
		KBUILD_BUILD_VERSION="$((pkgrel + 1))-postmarketOS"
}

package() {
	mkdir -p "$pkgdir"/boot

	# The bootloader does not support zipped kernels
	make install dtbs_install modules_install \
		ARCH="$_carch" \
		LLVM=1 \
		INSTALL_PATH="$pkgdir"/boot \
		INSTALL_MOD_PATH="$pkgdir"/usr \
		INSTALL_MOD_STRIP=1 \
		INSTALL_DTBS_PATH="$pkgdir"/boot/dtbs
	rm -f "$pkgdir"/usr/lib/modules/*/build "$pkgdir"/usr/lib/modules/*/source

	install -D "$builddir"/include/config/kernel.release \
		"$pkgdir"/usr/share/kernel/"$_flavor"/kernel.release

	install -Dm644 "$builddir"/arch/"$_carch"/boot/Image \
		"$pkgdir"/boot/vmlinuz
}

sha512sums="
a12a16c08c8867397c69c8eeb5a1a9195253cbcce8d0a9cc731c24d027d79040a9d2b598bcc2c6fca0f4a1f019216e652d2fc1a00025b15c064b7165a61ee9c3  linux-6.15.tar.gz
6ae251c24451851480a44f754cc1c7d07aef698c177b850c5f45f7018c767803c4609add27e5d9a747140e692180ad76f057e471cf0d3038e05050e40d8ea6db  patches-5686e3b545bd34e80ec6e73604b8819d10e52a2c.tar.gz
8601e1eb16aa0e3f9ddc52f8ef719c3c882759c80fc391aafa0ca900247368f21e3d0244f44922bab7fafbf705811cf4c91877c098af562685dbb054322377ba  config-postmarketos-exynos7870.aarch64
"
