#!/usr/bin/env bash

device="/dev/mapper/volgroup-cryptarchroot"
tpm_device="auto"
pcrs=(0 2 3 4 5 7 12)

tpm_keys=$(systemd-cryptenroll $device | grep -c "tpm2")

# If there are less than 2 TPM keys, exit
if [ "$tpm_keys" -lt 2 ]; then
  echo "Only $tpm_keys TPM keys found. Not deleting any"
else
  delete_slot=$(systemd-cryptenroll --no-pager $device | grep tpm2 | tail -n 1 | awk '{print $1}')
  systemd-cryptenroll --no-pager "$device" --wipe "$delete_slot"
fi

systemd-cryptenroll "$device" --unlock-tpm2-device="$tpm_device" --tpm2-device="$tpm_device" --tpm2-pcrs="$(
  IFS=+
  echo "${pcrs[*]}"
)"
