#!/usr/bin/bash
# SPDX-License-Identifier: MIT
set -euo pipefail

# TODO(systemd>=262): Evaluate the cryptenroll Varlink API / native firstboot
# wizard as replacement for this prompt coordinator.
[[ ! -e /var/lib/image/tpm-enrolled ]] || exit 0
systemd-analyze condition ConditionSecurity=uefi-secureboot ConditionSecurity=measured-uki
device="$(cryptsetup status root | sed -n 's/^[[:space:]]*device:[[:space:]]*//p')"
[[ -b ${device} ]] && cryptsetup isLuks "${device}"
[[ -r /run/systemd/tpm2-pcr-public-key.pem && -r /run/systemd/tpm2-pcr-signature.json ]]
/usr/lib/systemd/systemd-pcrlock --quiet is-supported

# Reuse the normal, short-lived cryptsetup kernel password cache when possible.
key=/run/image-tpm-enroll/passphrase
trap 'rm -f -- "$key"' EXIT
umask 0077
cache_options=(--accept-cached)
while true; do
    # Force agent routing: Plymouth owns the keyboard while the splash is up;
    # the console agent handles the same request when Plymouth is disabled.
    systemd-ask-password --no-tty -n --timeout=120 --keyname=cryptsetup \
        "${cache_options[@]}" 'Authorize TPM disk enrollment with your disk passphrase:' >"${key}"
    if cryptsetup open --test-passphrase --key-file="${key}" "${device}"; then
        break
    fi
    # The shared cache may contain another volume's password.
    cache_options=()
    rm -f -- "${key}"
    echo 'image: passphrase does not unlock USER; asking again' >&2
done
/usr/lib/image-pcrlock-update
systemd-cryptenroll --unlock-key-file="${key}" --tpm2-device=auto --tpm2-pcrs= \
    --tpm2-public-key=/run/systemd/tpm2-pcr-public-key.pem \
    --tpm2-public-key-pcrs=11 --tpm2-signature=/run/systemd/tpm2-pcr-signature.json \
    --tpm2-pcrlock=/var/lib/systemd/pcrlock.json "${device}"
install -d -m 0700 /var/lib/image
touch /var/lib/image/tpm-enrolled
echo 'image: TPM enrollment completed; the human passphrase remains available'
