#!/bin/sh

boot_files_directory () {
   LIVE_IMAGE_MOUNTPOINT=/lib/live/mount/medium
   if [ -d "$LIVE_IMAGE_MOUNTPOINT" ]; then
      echo "$LIVE_IMAGE_MOUNTPOINT"
   else
      echo ''
   fi
}

for arg in $(cat /proc/cmdline) ; do
   case "$arg" in
      BOOT_IMAGE=*)
         kernel="${arg#BOOT_IMAGE=}"
	 ;;
      initrd=*)
         initrd="${arg#initrd=}"
	 ;;
   esac
done

# GRUB2 does not pass initrd= on the kernel command-line.
if [ -z "$initrd" ]; then
   initrd=$(echo -n "$kernel" | sed -r -e 's,vmlinuz,initrd.img,')
fi

# Sanity checks
[ -n "$kernel" ] || exit 4
[ -n "$initrd" ] || exit 5

# Depending on the partition layout and GRUB2 configuration being used,
# BOOT_IMAGE= on the kernel command-line may point to a non-existing file,
# due to lacking the leading /boot; let's try harder if that's the case.
if [ ! -e "$kernel" -a -e "/boot$kernel" ]; then
   kernel="/boot$kernel"
   initrd="/boot$initrd"
fi

case "$1" in
   kernel)
      echo "$(boot_files_directory)${kernel}"
      ;;
   initrd)
      echo "$(boot_files_directory)${initrd}"
      ;;
   *)
      echo "Usage: $0 kernel|initrd" >&2
      exit 3
esac

exit 0
