#!/bin/sh

set -eu

mountpoint_override=''
if [ $# -ge 1 ]; then
  mountpoint_override="$1"
fi

read cmdline < /proc/cmdline

boot_device=''
bootsystem_mountpoint=''
lookup_image_path=true
puavo_image_path=''

for x in $cmdline; do
  case "$x" in
    puavo.image.path=*)
      puavo_image_path="${x#puavo.image.path=}"
      ;;
    root=/dev/mapper/puavo-images)
      bootsystem_mountpoint='/images'
      lookup_image_path=false
      ;;
    root=/dev/mapper/puavoinstaller-installimages)
      bootsystem_mountpoint='/installimages'
      lookup_image_path=false
      ;;
    root=/dev/nbd*)
      boot_device="${x#root=}"
      ;;
  esac
done

if [ -n "$boot_device" ]; then
  printf "%s\n" "$boot_device"
  exit 0
fi

if $lookup_image_path; then
  if [ -z "$puavo_image_path" ]; then
    echo 'ERROR: no image path, can not lookup boot device' >&2
    exit 1
  fi

  bootsystem_mountpoint=${puavo_image_path#/*}
  bootsystem_mountpoint="/${bootsystem_mountpoint%%/*}"
fi

# If the mountpoint is overridden, we must look for that mountpoint explicitly.
# Even if we know the current boot device, it might not have that mountpoint.
if [ -n "$mountpoint_override" ]; then
  bootsystem_mountpoint="$mountpoint_override"
else
  if [ -n "$boot_device" ]; then
    printf "%s\n" "$boot_device"
    exit 0
  fi
fi

if [ -z "$bootsystem_mountpoint" ]; then
  echo 'ERROR: boot system mountpoint is unknown' >&2
  exit 1
fi

disk_devpaths=$(
  lsblk -J -O | jq --arg mntpoint "$bootsystem_mountpoint" -r '
    [
      .blockdevices[]
        | select(.type == "disk" or .type == "loop")
        | {
            "mountpoints": [
              (.. | (.mountpoints? // []) | flatten[] | values)
            ],
            "path": .path
          }
        | select(.mountpoints[] == $mntpoint)
        | .path
    ] | unique | .[]
  ')

if [ -z "$disk_devpaths" ]; then
  echo 'ERROR: failed to find the boot disk(s)' >&2
  exit 1
fi

printf "%s\n" "$disk_devpaths"
