#!/usr/bin/bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2026 Tobias Görgens

set -euo pipefail
umask 0077

pcrlock=/usr/lib/systemd/systemd-pcrlock
policy=/var/lib/systemd/pcrlock.json
component=/var/lib/pcrlock.d/825-cryptsetup-root.pcrlock

[[ -x "${pcrlock}" ]] || exit 1
# systemd-pcrlock does not synthesize a component for the
# volume-key measurement written to PCR 15. Keep the component in /var so it is
# tied to this encrypted installation rather than shipped in the image.
# TODO(systemd#42748): Replace this CEL parsing with the native volume-key lock
# command/component once systemd-pcrlock provides one.
if [[ ! -f "${component}" ]]; then
    digest="$(
        "${pcrlock}" cel |
            jq -er '
                [
                    .[]
                    | select(.content.eventType == "volume-key")
                    | .digests[]
                    | select(.hashAlg == "sha256")
                    | .digest
                ]
                | unique
                | if length == 1 then
                    .[0]
                  else
                    error("expected exactly one SHA-256 volume-key measurement")
                  end
            '
    )"

    install -d -m 0755 /var/lib/pcrlock.d
    temporary="$(mktemp --tmpdir=/var/lib/pcrlock.d .825-cryptsetup-root.XXXXXX)"
    trap 'rm -f "${temporary:-}"' EXIT
    jq -cn --arg digest "${digest}" \
        '{records: [{pcr: 15, digests: [{hashAlg: "sha256", digest: $digest}]}]}' \
        >"${temporary}"
    chmod 0644 "${temporary}"
    mv -f "${temporary}" "${component}"
    trap - EXIT
fi

# Firmware/Secure Boot components may be intentionally removed by fwupd.
# Native non-strict prediction drops unavailable PCRs until boot services restore
# their components. Do not make PCR 0/7 mandatory during this update transition.
# Retain the root-volume measurement and verify PCR 15 before enrollment.
prediction="$(
    "${pcrlock}" --json=short --pcr=0 --pcr=7 --pcr=15 predict
)"
jq -e 'any(.[][]; .pcr == 15)' <<<"${prediction}" >/dev/null

# Use the same native credential publication as fwupd's MakePolicy calls.
# TODO(systemd#42748): Revisit native public-only publication when available;
# all CLI and Varlink policy writers must use the same mechanism.
"${pcrlock}" --policy="${policy}" make-policy --pcr=0 --pcr=7 --pcr=15
chmod 0600 "${policy}"
jq -e 'any(.pcrValues[]; .pcr == 15)' "${policy}" >/dev/null
