# Maintainer: Wang Zhiyu <pluvium27@outlook.com>
# Based on https://git.alpinelinux.org/aports/tree/main/linux-rpi/APKBUILD
# This package will provide linux-openstick & linux-openstick-dev QwQ

maintainer="Wang Zhiyu <pluvium27@outlook.com>"
pkgname=linux-openstick
pkgver=5.15.0
_kernver=${pkgver%.*}
pkgrel=0
pkgdesc="Linux kernel for OpenStick Project"
url="https://github.com/OpenStick/linux"
depends="initramfs-generator linux-firmware-brcm"
_depends_dev="perl gmp-dev elfutils-dev bash mpc1-dev mpfr-dev"
makedepends="$_depends_dev gcc>=13.1.1_git20230603 sed installkernel bc linux-headers linux-firmware-any
	bison flex openssl-dev>3 findutils xz mawk
"
options="!strip !check !checksum"
_openstick_repo="https://github.com/OpenStick/linux.git"
_linux_repo="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git"
# https://github.com/OpenStick/linux/archive/refs/tags/v5.15-msm8916.tar.gz is about 189.12M
source="https://github.com/OpenStick/linux/archive/refs/tags/v5.15-msm8916.tar.gz
common-changes.config"
arch="armhf aarch64"
license="GPL-2.0-only"
builddir="$srcdir"/linux-$_kernver-msm8916
_flavors="openstick"

for _f in $_flavors; do
	if [ "linux-$_f" != "$pkgname" ]; then
		subpackages="$subpackages linux-$_f::$CBUILD_ARCH"
	fi
	subpackages="$subpackages linux-$_f-dev:_dev:$CBUILD_ARCH"
done

case "$CARCH" in
	aarch64) _carch="arm64" ;;
	arm*) _carch="arm" ;;
esac

prepare() {
	default_prepare

	# remove localversion from patch if any
	rm -f localversion*

	local flavor=
	for flavor in $_flavors; do
		local _builddir="$srcdir"/build-$flavor.$CARCH
		mkdir -p "$_builddir"
		echo "-$pkgrel-$flavor" > "$_builddir"/localversion-alpine
		_genconfig $flavor
		make -C "$builddir" \
			O="$_builddir" \
			ARCH="$_carch" \
			olddefconfig
		_verifyconfig $flavor
	done
}

_genconfig() {
	# arch/arm/configs/msm8916_defconfig.part told me to do so
	cat "$builddir"/arch/arm64/configs/msm8916_defconfig "$builddir"/arch/arm/configs/msm8916_defconfig.part > "$builddir"/arch/arm/configs/msm8916_defconfig
	local flavor=$1 defconfig=
	local _builddir="$srcdir"/build-$flavor.$CARCH
	local defconfig=
	case "$CARCH" in
		armhf) defconfig=msm8916_defconfig;;
		aarch64) defconfig=msm8916_defconfig;;
		*) die "Unknown CARCH: $CARCH" ;;
	esac

	cp "$builddir"/arch/$_carch/configs/$defconfig \
		"$_builddir"/.config

	while read line; do
		# skip comments
		case "$line" in
			"#"*) continue;;
		esac
		local option=${line%%=*} str=
		local cmd=$(echo $line | cut -d= -f2)
		case "$cmd" in
			y) cmd="enable";;
			n) cmd="disable";;
			m) cmd="module";;
			'"'*) cmd="set-str"; str="${line#*=}";;
			[0-9]*) cmd="set-val"; str="${line#*=}";;
			*) die "Command $cmd not accepted" ;;
		esac
		msg "[$flavor] $cmd: $option $str"
		"$srcdir"/linux-$_kernver/scripts/config \
			--file "$_builddir"/.config \
			--$cmd "$option" "${str//\"/}"
	done < "$srcdir"/common-changes.config
}

# verify if options are set to correct value
_verifyconfig() {
	local flavor=$1
	local _builddir="$srcdir"/build-$flavor.$CARCH
	while read line; do
		[ ${line:0:1} = "#" ] && continue
		local option=${line%%=*} str= invert=
		local cmd=$(echo $line | cut -d= -f2)
		case "$cmd" in
			enable) str="$option=y" ;;
			disable) str="$option"; invert="-v" ;;
			module) str="$option=m" ;;
			set-val) str="$option=${line##*=}" ;;
			set-str) str=${line##*=}
				str="$option=\"${str//\"/}\"" ;;
		esac
		grep -q $invert "^$str" "$_builddir"/.config || \
			die "Config: $option not properly set!"
	done < "$srcdir"/common-changes.config
}

build() {
	unset LDFLAGS
	# for some reason these sometimes leak into the kernel build,
	# -Werror=format-security breaks some stuff
	unset CFLAGS CPPFLAGS CXXFLAGS
	for i in $_flavors; do
		cd "$srcdir"/build-$i.$CARCH
		local _kver=$(make kernelversion)
		if [ "$_kver" != "$pkgver" ]; then
			error "Version in Makefile ($_kver) does not correspond with pkgver ($pkgver)"
			return 1
		fi
		make ARCH="$_carch" CC="${CC:-gcc}" \
			AWK=mawk \
			KBUILD_BUILD_VERSION="$((pkgrel + 1 ))-Alpine"
	done
}

_package() {
	local _buildflavor="$1" _outdir="$2"
	local _builddir="$srcdir"/build-$_buildflavor.$CARCH

	cd "$_builddir"
	local _abi_release="$(make -s kernelrelease)"
	mkdir -p "$_outdir"/boot "$_outdir"/lib/modules

	local _install
	case "$CARCH" in
	arm*)
		_install="zinstall dtbs_install"
		;;
	aarch64)
		_install="install dtbs_install"
		;;
	*)
		_install=install
		;;
	esac

	# modules_install seems to regenerate a defect Modules.symvers. Work
	# around it by backing it up and restore it after modules_install
	cp Module.symvers Module.symvers.backup

	local INSTALL_DTBS_PATH="$_outdir"/boot
	make modules_install $_install \
		ARCH="$_carch" \
		INSTALL_MOD_PATH="$_outdir" \
		INSTALL_PATH="$_outdir"/boot \
		INSTALL_DTBS_PATH="$INSTALL_DTBS_PATH"
	cp Module.symvers.backup Module.symvers

	rm -f "$_outdir"/lib/modules/$_abi_release/build \
		"$_outdir"/lib/modules/$_abi_release/source
	rm -rf "$_outdir"/lib/firmware

	install -D -m644 include/config/kernel.release \
		"$_outdir"/usr/share/kernel/$_buildflavor/kernel.release

	ln -sf /boot/vmlinuz-"$_buildflavor" \
		"$_outdir"/lib/modules/"$_abi_release"/vmlinuz

	# allow the initramfs generators to know the package name the kernel came from
	echo "${subpkgname:-$pkgname}" > "$_outdir"/lib/modules/$_abi_release/pkgname

	if [ "$CARCH" = "aarch64" ]; then
		mv -f "$INSTALL_DTBS_PATH"/broadcom/*.dtb \
			"$INSTALL_DTBS_PATH"
		rmdir "$INSTALL_DTBS_PATH"/broadcom
	fi
}

# main flavor installs in $pkgdir
package() {
	case "$CARCH" in
	armv7)
		provides="linux=$pkgver-r$pkgrel"  # for backward compatibility
		replaces="linux"  # for backward compatibility
	;;
	aarch64)
		provides="linux=$pkgver-r$pkgrel"  # for backward compatibility
		replaces="linux"  # for backward compatibility
	;;
	esac
	_package openstick "$pkgdir"
}


_dev() {
	local _flavor=$(echo $subpkgname | sed -E 's/(^linux-|-dev$)//g')
	local _builddir="$srcdir"/build-$_flavor.$CARCH

	cd "$_builddir"
	local _abi_release="$(make -s kernelrelease)"
	# copy the only the parts that we really need for build 3rd party
	# kernel modules and install those as /usr/src/linux-headers,
	# simlar to what ubuntu does
	#
	# this way you dont need to install the 300-400 kernel sources to
	# build a tiny kernel module
	#
	pkgdesc="Headers and script for third party modules for $_flavor kernel"
	depends="$_depends_dev"

	# handle backward compatibility with legacy flavors
	case "$_flavor" in
		openstick)
			case "$CARCH" in
				armv7)
					provides="linux-dev=$pkgver-r$pkgrel"
					replaces="linux-dev"
				;;
				aarch64)
					provides="linux-dev=$pkgver-r$pkgrel"
					replaces="linux-dev"
				;;
			esac
			;;
		*) die "Unknown flavor: $flavor" ;;
	esac

	local dir="$subpkgdir"/usr/src/linux-headers-$_abi_release

	# first we import config, run prepare to set up for building
	# external modules, and create the scripts
	mkdir -p "$dir"
	cp "$_builddir"/.config "$dir"/.config
	echo "-$pkgrel-$_flavor" > "$dir"/localversion-alpine

	make -j1 -C "$builddir" ARCH="$_carch" O="$dir" \
		syncconfig prepare modules_prepare scripts

	# remove the stuff that points to real sources. we want 3rd party
	# modules to believe this is the soruces
	rm "$dir"/Makefile "$dir"/source

	# copy the needed stuff from real sources
	#
	# this is taken from ubuntu kernel build script
	# http://kernel.ubuntu.com/git/ubuntu/ubuntu-zesty.git/tree/debian/rules.d/3-binary-indep.mk
	cd "$builddir"
	find .  -path './include/*' -prune \
		-o -path './scripts/*' -prune -o -type f \
		\( -name 'Makefile*' -o -name 'Kconfig*' -o -name 'Kbuild*' -o \
		   -name '*.sh' -o -name '*.pl' -o -name '*.lds' \) \
		-print | cpio -pdm "$dir"

	cp -a scripts include "$dir"
	find $(find arch -name include -type d -print) -type f \
		| cpio -pdm "$dir"

	install -Dm644 "$_builddir"/Module.symvers \
		"$dir"/Module.symvers

	mkdir -p "$subpkgdir"/lib/modules/$_abi_release
	ln -sf /usr/src/linux-headers-$_abi_release \
		"$subpkgdir"/lib/modules/$_abi_release/build
}

sha512sums="734d958bb9fa64e667e089aec0066a58526ae38fbf6fbd223a7bce746fe3ce7443ffe087f365a44f6892479186f2c0eb33abacd38eb7b0b8d40949602812e441  v5.15-msm8916.tar.gz
cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e  common-changes.config" # common-changes.config is empty, make sure checksums are currected after any modification!
