#!/bin/bash

# There is a cryptsetup-pre.target that can be used, but is not
# easy execute the service when the ESP device is ready and the
# systemd-cryptsetup service was still not executed
# (cryptsetup.target).  The solution is to use a generator, that
# will after/requires from dev-disk-by-partuuid-XXX, where XXX
# comes from LoaderDevicePartUUID efivar.

set -euo pipefail

# For a generator, the first parameter `normal-dir` is not optional
[ -n "$1" ] || { echo "Missing normal-dir parameter"; exit 1; }

# Only intended to run in the initrd
[ -e "/etc/initrd-release" ] || exit 0

# If GRUB2 is used, bli.mod needs to be loaded
EFIVAR="/sys/firmware/efi/efivars/LoaderDevicePartUUID-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f"

[ -e "$EFIVAR" ] || exit 0

# Read the value of the EFI variable, that contains a header and ends
# with '\0' and make it lowercase
ESP_UUID="$(dd "if=$EFIVAR" bs=2 skip=2 conv=lcase status=none | tr -d '\0')"
DEV="/dev/disk/by-partuuid/${ESP_UUID}"

cat > "$1/boot-efi.mount" <<EOF
# Automatically generated by boot-efi-generator

[Unit]
Description=ESP (/boot/efi)
Conflicts=initrd-switch-root.target
Before=initrd-switch-root.target
DefaultDependencies=false

[Mount]
What=$DEV
Where=/boot/efi
Type=vfat
Options=utf8
EOF
