#!/bin/bash
set -euo pipefail

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

[ -f "/etc/crypttab" ] || exit 0;

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

# Read /etc/crypttab lines that contains tpm2-device and
# tpm2-measure-pcr.  It will order the services as listed in this file
after=""
while read -r name _ _ opts; do
	[[ "$name" = \#* ]] && continue
	[[ "$opts" != *"tpm2-device="* ]] && continue
	[[ "$opts" != *"tpm2-measure-pcr="* ]] && continue
	mkdir -p "$1/systemd-cryptsetup@$name.service.d"
	cat > "$1/systemd-cryptsetup@$name.service.d/measure-pcr.conf" <<-EOF
	# Automatically generated by measure-pcr-generator

	[Service]
	Environment="SYSTEMD_FORCE_MEASURE=yes"
	EOF
	if [ -n "$after" ]; then
		cat >> "$1/systemd-cryptsetup@$name.service.d/measure-pcr.conf" <<-EOF

		[Unit]
		After=systemd-cryptsetup@$after.service
		EOF
	fi
	after="$name"
done < /etc/crypttab

# Do a similar loop for devices that can be unlocked by FIDO2 keys
after=""
while read -r name _ _ opts; do
	[[ "$name" = \#* ]] && continue
	[[ "$opts" != *"fido2-device="* ]] && continue
	mkdir -p "$1/systemd-cryptsetup@$name.service.d"
	[ -f "$1/systemd-cryptsetup@$name.service.d/measure-pcr.conf" ] || {
		echo "# Automatically generated by measure-pcr-generator" > "$1/systemd-cryptsetup@$name.service.d/measure-pcr.conf"
	}
	if [ -n "$after" ]; then
		cat >> "$1/systemd-cryptsetup@$name.service.d/measure-pcr.conf" <<-EOF

		[Unit]
		After=systemd-cryptsetup@$after.service
		EOF
	fi
	after="$name"
done < /etc/crypttab
