#!/bin/bash
#######################################
# Detects and collects all boot devices for GRUB installation.
# Supports /dev/sdX, /dev/vdX, /dev/hdX, /dev/nvmeXn1, /dev/mmcblkX.
# Globals:
#   VAR_RECIPE_HIGHEST_DEVICE
#   ary_bootdev_all
#   grub_bootdev
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
get_all_boot_devs() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -ag ary_bootdev_all=()
  declare     dev="" dev_prefix="" dev_path="" letter=""
  declare -i  ascii=0 ascii_end=0 ascii_start=0

  ### Determine prefix from grub_bootdev (e.g., "sd", "vd", "nvme", "mmcblk")
  dev_prefix=$(basename "${grub_bootdev}" | sed -E 's/^([a-z]+)[a-z0-9]*$/\1/')

  case "${dev_prefix}" in

    sd|vd|hd)
      ascii_start=$(printf '%d' "'a")
      ascii_end=$(printf '%d' "'${VAR_RECIPE_HIGHEST_DEVICE}")
      for ((ascii = ascii_start; ascii <= ascii_end; ascii++)); do
        letter=$(printf "%b" "\\$(printf '%03o' "${ascii}")")
        dev_path="/dev/${dev_prefix}${letter}"
        [[ -b "${dev_path}" ]] && ary_bootdev_all+=("${dev_path}")
      done
      ;;

    nvme)
    # shellcheck disable=SC2312
      while read -r dev; do
        ary_bootdev_all+=("/dev/${dev}")
      done < <(lsblk -dn -o NAME | grep -E '^nvme[0-9]+n1$')
      ;;

    mmcblk)
    # shellcheck disable=SC2312
      while read -r dev; do
        ary_bootdev_all+=("/dev/${dev}")
      done < <(lsblk -dn -o NAME | grep -E '^mmcblk[0-9]+$')
      ;;

    *)
      do_log "warning" "file_only" "4230() Unrecognized boot device prefix: ${dev_prefix}"
      ;;

  esac

  return 0
}
