# Extra packages required in this snippet:
#  * clevis-dracut

LOG_FILE=/root/postinstall-clevis-tpm2.log
[ -n "@NO_SAVE@" ] && LOG_FILE=/dev/null

exec < /dev/tty3 > /dev/tty3
chvt 3
echo "######################"
echo "# %post clevis-tpm2  #"
echo "######################"
(
  CLEVIS_PIN='tpm2'
  CLEVIS_CONFIG='{}'
  PROFILER='@PROFILER@'
  REQ_PKGS='clevis-dracut'

  # Sanity check.
  skip=
  for _pkg in ${REQ_PKGS}; do
    rpm -q "${_pkg}" >/dev/null || skip=true
  done

  # Save current directory.
  CWD="$(pwd)"
  # Move to /root, so that any logs/files written locally will be preserved.
  cd /root

  if [ -z "${skip}" ]; then
    # Validate the configuration.
    clevis_cfg="$(jose fmt -j "${CLEVIS_CONFIG}" -Oo-)"

    # Bind all LUKS devices
    max_attempts=10
    for dev in $(blkid -t TYPE=crypto_LUKS -o device); do
      attempts=0
      # We may hit an issue in which the generation of the new passphrase
      # fails with "Error: Password generation failed - required entropy
      # too low for settings" - loop until the binding succeeds or 10 times
      # per device.
      # https://access.redhat.com/solutions/3486131
      until ${PROFILER} clevis luks bind -f -d "${dev}" "${CLEVIS_PIN}" "${clevis_cfg}" <<< '@LUKS_PW@'; do
        attempts=$((attempts+1))
        [ "${attempts}" -ge "${max_attempts}" ] && break
        sleep 0.1
      done
    done

    # Return to previous directory.
    cd "${CWD}"

    # Enable clevis-luks-askpass.
    systemctl enable clevis-luks-askpass.path ||:

    dracut -f --regenerate-all
  else
    echo "##################################################################"
    echo "#    Kickstart snippet skipped. Please make sure the required    #"
    echo "# variables are defined and the required packages are installed. #"
    echo "##################################################################"
    echo
    echo "* Required variables:"
    echo "(none)"
    echo
    echo "* Required packages: ${REQ_PKGS}"
    echo
    echo "* Installed packages:"
    rpm -qa | sort
    echo
  fi
) 2>&1 | tee "${LOG_FILE}"
chvt 1

# vim:set ts=2 sw=2 et:

