#!/bin/sh

. /usr/bin/next_boot_mount_point

UPGRADE_OR_ROLLBACK_FILE="/var/lib/cumulus/image-upgrade/upgrade-or-rollback"

if [ ! -z ${kernel:+x} ]; then
    vmlinuz="/boot/vmlinuz-$kernel"
    initrd="--initrd=/boot/initrd.img-$kernel"
else
    vmlinuz="$(realpath /vmlinuz)"
    initrd="--initrd=$(realpath /initrd.img)"
fi

kargs="$vmlinuz $initrd"
cmdline=$(cat /proc/cmdline)
kexec_args=""

# Secure boot capable systems need an additional acpi_rsdp argument and kexec arg
if [ -e /sys/firmware/efi/systab ]; then
	acpi_rsdp="acpi_rsdp=$(grep -m1 ^ACPI /sys/firmware/efi/systab | cut -f2- -d=)"
	if ! grep -q "$acpi_rsdp" /proc/cmdline; then
		cmdline="$cmdline $acpi_rsdp"
	fi
	kexec_args="-s"
fi

# Determine the next boot partition UUID and update cmdline accordingly
next_boot_uuid=$( grep UUID= /boot/grub/grub.cfg | head -1 | sed -e 's/^.*root=UUID=//' -e 's/ .*$//' )
cmdline=$(echo "${cmdline}" | sed -e "s/UUID=\([a-fA-F0-9-]\)* /UUID=$next_boot_uuid /g" )

echo "kboot: next_boot_uuid: $next_boot_uuid"
echo "kboot: cmdline passed to kexec after updating boot partition uuid: $cmdline"

if [ -f $UPGRADE_OR_ROLLBACK_FILE ] && grep -q "upgrade" $UPGRADE_OR_ROLLBACK_FILE;
then
    echo "kboot: This is ISSU with A/B partitions. So, picking kernel from the target partition"
    mountpoint="/mnt/next_kernel_partition"
    createMountPointForNextBootPartition $mountpoint
    vmlinuz=$(ls $mountpoint/boot/vmlinuz*)
    echo "kboot: Updated vmlinuz based on kernel from target partition: $vmlinuz"

    kargs="$vmlinuz $initrd"
    echo "kboot: Updated kargs based on kernel from target partition: $kargs"
else
    # The fact that the execution came to kexec path indicates it is either
    # going through fast-reboot/warm-reboot in the same version or
    # apt upgrade based ISSU or ISSU with A/B partitions.
    # If it is ISSU with A/B partitions, the UPGRADE_OR_ROLLBACK_FILE
    # gets created and it will have "upgrade" written in it.
    echo "kboot: Either this is not A/B upgrade OR Could not accesss the file: $UPGRADE_OR_ROLLBACK_FILE"
fi

# change BOOT_IMAGE argument in case it points to old kernel
cmdline=$(echo "${cmdline}" | sed -e "s|BOOT_IMAGE=/boot/vmlinuz-$(uname -r) |BOOT_IMAGE=$vmlinuz |g" )

kexec $kexec_args -t bzImage -l $kargs --append="$cmdline $*"
systemctl kexec
