# Maintainer: Antoine Martin (ayakael) <dev@ayakael.net>
# Contributor: Antoine Martin (ayakael) <dev@ayakael.net>

pkgname=linux-rm
pkgver=5.4.70
_rmver=1.3.4
pkgrel=11
pkgdesc="Linux kernel with reMarkable patches"
url=https://github.com/reMarkable/linux
depends="initramfs-generator linux-firmware-brcm linux-firmware-cypress"
_depends_dev="perl gmp-dev elfutils-dev bash mpc1-dev mpfr-dev"
makedepends="$_depends_dev sed installkernel bc linux-headers linux-firmware mawk
	bison flex openssl-dev>3 diffutils pahole findutils xz lzop
"
options="!strip !check"
builddir="$srcdir"/linux-RM1XX_${pkgver}_v$_rmver
source="
	https://github.com/reMarkable/linux/archive/refs/tags/RM1XX_${pkgver}_v$_rmver.tar.gz
	https://raw.githubusercontent.com/ichaozi/RemarkableFramebuffer/0f37dc8c06d340dc1af52ff2d4d6d5789ccf14bb/kernel-mxc-epdc-fb-reference/epdc_ES103CS1.fw
	arm-replace-sun-style-flash-on-section-directive.patch
	brcmfmac-disable-power-management.patch
	brcmfmac-fix-suspend-resume-when-power-is-cut-off.patch
	enable-automatic-partial-refreshing.patch
	config-changes-rm.armv7
	config-changes-rm.armhf
	"
arch="armv7"
license="GPL-2.0"
for _i in $source; do
	case $_i in
	config-*.$CARCH)
		_f=${_i%."$CARCH"}
		_f=${_f#config-changes-}
		_flavors="$_flavors $_f"
		[ "linux-$_f" != "$pkgname" ] && subpackages="$subpackages linux-$_f::$CTARGET_ARCH"
		subpackages="$subpackages linux-$_f-dev:_dev:$CTARGET_ARCH"
		;;
	esac
done

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

# generate config from defconfig and apply local changes.
# config-changes-$flavor.$CARCH holds a list of = delimited
# config command and values used by kernel scripts/config script.
_genconfig() {
	local flavor=$1 defconfig=
	local subbuilddir="$srcdir"/build-$flavor
	local defconfig=
	case $flavor in
		rm) defconfig=zero-gravitas_defconfig ;;
		rm2) defconfig=zero-sugar_defconfig ;;
		*) die "Unknown flavor: $flavor" ;;
	esac

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

	while read -r 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"
		"$builddir"/scripts/config \
			--file "$subbuilddir"/.config \
			--$cmd "$option" "${str//\"/}"
	done < "$srcdir"/config-changes-$flavor.$CARCH
}

# verify if options are set to correct value
_verifyconfig() {
	local flavor=$1
	local subbuilddir="$srcdir"/build-$flavor
	while read -r 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" "$subbuilddir"/.config || \
			die "Config: $option not properly set!"
	done < "$srcdir"/config-changes-$flavor.$CARCH
}

prepare() {
	default_prepare

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

build() {
	unset LDFLAGS
	for i in $_flavors; do
		cd "$srcdir"/build-$i
		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}" KLZOP="/usr/bin/lzop" \
			KBUILD_BUILD_VERSION="$((pkgrel + 1 ))-Alpine"
	done
}

_package() {
	local _flavor="$1" _outdir="$2"
	local _builddir="$srcdir"/build-$_flavor
	local _abi_release="$(make -C "$_builddir" -s kernelrelease)"

	cd "$srcdir"/build-$_flavor

	mkdir -p "$_outdir"/boot "$_outdir"/lib/modules

	local _install="zinstall dtbs_install"

	cd "$srcdir"/build-$_flavor
	# 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 -j1 modules_install $_install \
		ARCH="$_carch" \
		INSTALL_MOD_PATH="$_outdir" \
		INSTALL_MOD_STRIP=1 \
		INSTALL_PATH="$_outdir"/boot \
		INSTALL_DTBS_PATH="$INSTALL_DTBS_PATH"
	cp Module.symvers.backup Module.symvers

	cp "$_builddir"/arch/arm/boot/zImage "$_outdir"/boot/zImage
	rm "$_outdir"/boot/vmlinuz-$_flavor

	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/$_flavor/kernel.release

	# install missing firmware
	install -vDm644 "$srcdir"/epdc_ES103CS1.fw "$_outdir"/lib/firmware/imx/epdc/epdc_ES103CS1.fw
}

# main flavor installs in $pkgdir
package() {
	_package rm "$pkgdir"
}

# subflavors install in $subpkgdir
rm2() {
	depends="initramfs-generator linux-firmware-brcm linux-firmware-cypress"
	_package rm2 "$subpkgdir"
}

_dev() {
	local _flavor=$(echo $subpkgname | sed -E 's/(^linux-|-dev$)//g')
	local _builddir="$srcdir"/build-$_flavor
	local _abi_release="$(make -C "$_builddir" -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"
	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" \
		O="$dir" \
		ARCH="$_carch" \
		AWK="${AWK:-mawk}" \
		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

	# scripts aren't being crossbuilt from some reason
	if cross_compiling; then
		for i in $(scanelf -R "$dir"  | awk '{print $2}' | sed '1d'); do rm "$i"; done
	fi

	# 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"

	# shellcheck disable=SC2046
	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="
0409c8443f5a705e8254858f966eed571b935f1be952f64c1d74b52a043d0638ba358370ca20f665d69b70aabe06f03e0bfa02ccd1a4a2a174d5b9579a10b44e  RM1XX_5.4.70_v1.3.4.tar.gz
ad4bd6f332319aceee7a1c7b71b49439e8217621214b6249c7e20198360d02ea442f31edfc8e1af1b85ed71e6f97c1cb7decf7b0885c9d0293361eef47f218b2  epdc_ES103CS1.fw
f9114f8843317e1d26fbf1831182bc9c8d5907a92af6312c778f32be81414cfddfc3ced7b58375960232031d3295e8770b1a1e7466d2ace99e01bbcccd838543  arm-replace-sun-style-flash-on-section-directive.patch
c5fc4f2f70112cc66a91a2948f7fd4adcd7172a95191b4c862084c7b80093cfa696925aa9a825c41bddac7441ba153eb264b8146e52a4556a73349e6fd10e641  brcmfmac-disable-power-management.patch
27ec1bc1d916dbd2258192c1ed864eacbd2746b49caa554fbaf1124bac478bab0b729e7fabbab8705ae175bb098800f795d415f4de4964da921c1b802560b67a  brcmfmac-fix-suspend-resume-when-power-is-cut-off.patch
0f47278c5bfafb939e46224fbf16f9491e3cc560ac128dcf430a1f6cf9064fb1c5bf5db1a3076c35d30c004aec525a7d6616a647564f197bb29c57701c1db982  enable-automatic-partial-refreshing.patch
9d01054ea7e4ee43836cc536bead5c1707b133790a4ef63e29feb10de4e0b290ba8829980b5340f56bee1e9ec0de66e1e4a55f03c0e6aacbce871a9d60e6ef2e  config-changes-rm.armv7
9d01054ea7e4ee43836cc536bead5c1707b133790a4ef63e29feb10de4e0b290ba8829980b5340f56bee1e9ec0de66e1e4a55f03c0e6aacbce871a9d60e6ef2e  config-changes-rm.armhf
"
