#!/bin/sh

## Copyright 2022 Arnaud Ferraris <aferraris@debian.org>
##
## SPDX-License-Identifier: GPL-3.0-or-later

set -e

VERSION="$1"
if [ -z "${VERSION}" ]; then
    echo "Usage: $0 VERSION"
    exit 1
fi

BOOTPART="boot"
LATESTKERNEL="$(linux-version list | tail -1)"

# Only update the bootimg for the most recent kernel
if linux-version compare "${VERSION}" lt "${LATESTKERNEL}"; then
    echo "I: Not updating bootimg for ${VERSION} < ${LATESTKERNEL}, quitting..."
    exit 0
fi

# Fetch the device parameters
for x in $(cat /proc/cmdline); do
    case $x in
        mobile.qcomsoc=*) QCOMSOC=${x#mobile.qcomsoc=} ;;
        mobile.vendor=*) VENDOR=${x#mobile.vendor=} ;;
        mobile.model=*) MODEL=${x#mobile.model=} ;;
        mobile.variant=*) VARIANT=${x#mobile.variant=} ;;
    esac
done

if [ -z "${MODEL}" ]; then
    echo "Probably running in a VM, not updating bootimg..."
    exit 0
fi

if [ "${VARIANT}" ]; then
    DTBNAME="${QCOMSOC}-${VENDOR}-${MODEL}-${VARIANT}"
else
    DTBNAME="${QCOMSOC}-${VENDOR}-${MODEL}"
fi

ROOTUUID="$(findmnt -n -o UUID /)"
if [ -z "${ROOTUUID}" ]; then
    echo "W: Unable to determine root filesystem UUID, quitting..."
    exit 1
fi

if [ -e /dev/disk/by-partlabel/boot_b ]; then
    # Check slot currently in use: `abootimg -i` prints information about the
    # boot image, including the kernel cmdline it contains; if we can find the
    # UUID of the current root partition, then we can assume that's the one.
    # Otherwise, we just default to slot a
    if abootimg -i /dev/disk/by-partlabel/boot_a | grep -q "${ROOTUUID}"; then
        BOOTPART="boot_a"
    elif abootimg -i /dev/disk/by-partlabel/boot_b | grep -q "${ROOTUUID}"; then
        BOOTPART="boot_b"
    fi
fi

TMPDIR=$(mktemp -d /tmp/bootimg.XXXXXX)

# Append the DTB to the kernel
cat /boot/vmlinuz-${VERSION} /usr/lib/linux-image-${VERSION}/${DTBNAME}.dtb > ${TMPDIR}/kernel-${VERSION}

# Read the currently used boot image
dd if=/dev/disk/by-partlabel/${BOOTPART} of=${TMPDIR}/boot.img bs=1M

# Update the boot image and write it to disk
cd ${TMPDIR}
abootimg -x boot.img

abootimg -u boot.img -f bootimg.cfg -k kernel-${VERSION} -r /boot/initrd.img-${VERSION}
dd if=boot.img of=/dev/disk/by-partlabel/${BOOTPART} bs=1M

# Cleanup and exit
cd -
rm -rf ${TMPDIR}
