#!/bin/bash
set -ex
# Debian kernel hooks pass the kernel version as the first argument.
# Fall back to the newest installed kernel when invoked manually without it,
# so wildcard expansion never matches multiple kernel versions (see armbian/build#10108).
version="$1"
if [ -z "${version}" ]; then
	version=$(ls -1 /boot/vmlinuz-*-sm8250 2>/dev/null | sed 's|^/boot/vmlinuz-||' | sort -V | tail -n1)
fi
kernel="/boot/vmlinuz-${version}"
ramdisk="/boot/initrd.img-${version}"
if [ ! -f "${kernel}" ]; then
	echo "Kernel image not found: ${kernel}" >&2
	exit 1
fi
if [ ! -f "${ramdisk}" ]; then
	echo "Ramdisk not found: ${ramdisk}" >&2
	exit 1
fi
new_rootfs_image_uuid=$(sed -e 's/^.*root=UUID=//' -e 's/ .*$//' < /proc/cmdline)
gzip -c "${kernel}" > /tmp/Image.gz

cat /tmp/Image.gz /usr/lib/linux-image-${version}/qcom/sm8250-oneplus-kebab.dtb > /tmp/Image.gz-dtb

extraargs=""
abl_boot_partition_label=""
source /boot/armbianEnv.txt
/usr/bin/mkbootimg \
        --kernel /tmp/Image.gz-dtb \
        --ramdisk "${ramdisk}" \
        --base 0x0 \
        --second_offset 0x00f00000 \
        --cmdline "root=UUID=${new_rootfs_image_uuid} slot_suffix=${abl_boot_partition_label#boot} ${extraargs}" \
        --kernel_offset 0x8000 \
        --ramdisk_offset 0x1000000 \
        --tags_offset 0x100 \
        --pagesize 4096 \
        -o /boot/armbian-kernel.img
rm -f /tmp/Image.gz /tmp/Image.gz-dtb

if [ -n "$abl_boot_partition_label" ];then
	echo abl boot partition label is $abl_boot_partition_label
	dd if=/boot/armbian-kernel.img of=/dev/disk/by-partlabel/${abl_boot_partition_label}
else
	echo abl boot partition label is not defined, exit
	exit
fi
