#! /bin/sh
set -e

# grub-mkconfig helper script.
# Copyright (C) 2006,2007,2008,2009  Free Software Foundation, Inc.
# Copyright (C) 2020  Free Software Foundation, Inc.
# Copyright (C) 2026  Thomas Grainger <tagrain@gmail.com>
#
# Based on util/grub.d/30_os-prober.in and util/grub.d/30_uefi-firmware.in
#
# GRUB is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GRUB is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GRUB.  If not, see <http://www.gnu.org/licenses/>.

prefix="/usr"
exec_prefix="/usr"
datarootdir="/usr/share"

export TEXTDOMAIN=grub2
export TEXTDOMAINDIR="${datarootdir}/locale"

. "$pkgdatadir/grub-mkconfig_lib"

if [ x"${GRUB_INITRAMFS_KEYFILE}" = x ]; then
  exit 0
fi

if [ x$GRUB_ENABLE_CRYPTODISK != xy ]; then
  exit 0
fi

# GRUB_INITRAMFS_KEYFILE is a whitespace separated list of key file paths:
#   GRUB_INITRAMFS_KEYFILE="keyfile1 keyfile2 ... keyfile8"
# The cryptouuid is prepended below. Requirements:
# - at least one path and at most 8 paths
# - every path is absolute
# On invalid input, warn and skip generating initramfs_keyfile instead of
# aborting grub-mkconfig.

# Split on whitespace using the default IFS, without pathname expansion.
set -f
set -- ${GRUB_INITRAMFS_KEYFILE}
set +f

if [ "$#" -eq 0 ]; then
  exit 0
fi

if [ "$#" -gt 8 ]; then
  grub_warn "$(gettext "GRUB_INITRAMFS_KEYFILE cannot contain more than 8 key file paths. Ignoring it.")"
  exit 0
fi

# Wrap $1 in single quotes, escaping embedded single quotes as '\''.
initramfs_keyfile_quote ()
{
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

initramfs_keyfile_args=
for path in "$@"; do
  case "${path}" in
    /*)
      ;;
    *)
      grub_warn "$(gettext "GRUB_INITRAMFS_KEYFILE paths must be absolute. Ignoring it.")"
      exit 0
      ;;
  esac
  initramfs_keyfile_args="${initramfs_keyfile_args} $(initramfs_keyfile_quote "${path}")"
done

# Final format: initramfs_keyfile cryptouuid keyfilepath1 ... keyfilepath8
# Each argument is single-quoted so that GRUB does not expand special characters.
for uuid in `"${grub_probe}" --target=cryptodisk_uuid /boot`; do
  echo "initramfs_keyfile '${uuid}'${initramfs_keyfile_args}"
done
