#!/usr/bin/env bash

# References:
#  https://os.gnome.org/install
#  https://www.reddit.com/r/Fedora/comments/uo4ufq/any_way_to_get_systemdcryptenroll_working_on/
#  https://0pointer.net/blog/unlocking-luks2-volumes-with-tpm2-fido2-pkcs11-security-hardware-on-systemd-248.html

gum confirm --affirmative="Enable" --negative="Disable" "Toggle TPM2 auto-unlock"
EXIT_CODE="$?"
case "${EXIT_CODE}" in
  0|1)
    ;;
  *)
    exit 0
esac

RD_LUKS_UUID="$(xargs -n1 -a /proc/cmdline | grep -E -e "rd.luks.(uuid|name)" | head -n 1 | cut -d= -f 2 | sed "s/^luks-//" )"
CRYPT_DISK="$(realpath "/dev/disk/by-uuid/${RD_LUKS_UUID}")"

if ! find /dev -iname "${RD_LUKS_UUID:-INVALIDINVALID}" | grep -F -e "${RD_LUKS_UUID}" &>/dev/null; then
  echo "Could not find LUKS device used to boot system on system mount table. Is your drive encrypted?"
  exit 1
fi

if [ "${EXIT_CODE}" == 1 ] ; then
  sudo systemd-cryptenroll --wipe-slot=tpm2 "${CRYPT_DISK}"
  exit 0
fi

gum confirm "Would you like to set up a PIN?"
EXIT_CODE="$?"
SET_PIN_ARG=""
case "${EXIT_CODE}" in
  0)
    export SET_PIN_ARG="--tpm2-with-pin=yes"
    ;;
  1)
    ;;
  *)
    exit 0
esac

if sudo systemd-cryptenroll --wipe-slot=tpm2 --tpm2-device=auto --tpm2-pcrs='0+7+14' ${SET_PIN_ARG} "${CRYPT_DISK}" ; then
  echo "TPM2 LUKS auto-unlock configured for next reboot."
fi
