#!/bin/bash

## Copyright (C) 2023 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## Copyright (C) 2023 - 2023 Friedrich Doku <friedrichdoku@gmail.com>
## See the file COPYING for copying conditions.

#set -x
set -e

## Get the kernel command-line arguments
cmdline="$(cat -- /proc/cmdline)"

if [ "$cmdline" = "" ]; then
   printf "%s\n" "$0: ERROR: /proc/cmdline is empty!" >&2
   exit 1
fi

boot_image_full="$(printf "%s\n" "$cmdline" | grep -o 'BOOT_IMAGE=\S*')" || true
## example boot_image_full:
## BOOT_IMAGE=/vmlinuz-5.10.0-20-amd64
## BOOT_IMAGE=/boot/vmlinuz-5.10.0-20-amd64

if [ "$boot_image_full" = "" ]; then
   printf "%s\n" "$0: ERROR: /proc/cmdline does not contain BOOT_IMAGE!"  >&2
   exit 1
fi

boot_image=$(printf "%s\n" "$boot_image_full" | cut -d '=' -f 2)
## example boot_image:
## /vmlinuz-5.10.0-20-amd64
## /boot/vmlinuz-5.10.0-20-amd64

if [ "$boot_image" = "" ]; then
   printf "%s\n" "$0: ERROR: boot_image detection failed (is empty)!"
   exit 1
fi

boot_image_without_boot_slash=$(printf "%s\n" "$boot_image" | sed "s#/boot/##")

if [ "$boot_image_without_boot_slash" = "" ]; then
   printf "%s\n" "$0: ERROR: boot_image_without_boot_slash detection failed (is empty)!" >&2
   exit 1
fi

if test -r "/boot/$boot_image_without_boot_slash" ; then
   kernel="/boot/$boot_image_without_boot_slash"
elif test -r "/$boot_image_without_boot_slash" ; then
   kernel="/$boot_image_without_boot_slash"
fi
## example kernel:
## /boot/vmlinuz-5.10.0-20-amd64

initrd="$(printf "%s\n" "$kernel" | sed "s#vmlinuz#initrd.img#")"
## example initrd:
## /boot/initrd.img-5.10.0-20-amd64

if ! test -r "$kernel"; then
   printf "%s\n" "$0: ERROR: Kernel File '$kernel' not found or not readable!" >&2
   exit 1
fi

printf "%s\n" "$kernel"
