# Extra env variables for this snippet:
#  - CLEVIS_PIN
#  - CLEVIS_CONFIG
#
# Extra packages required in this snippet:
#  * clevis-dracut

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

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

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

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

    if [ "${CLEVIS_PIN}" = "tang" ]; then
      if ! jose fmt -j "${CLEVIS_CONFIG}" -Og adv \
           && ! jose fmt -j "${CLEVIS_CONFIG}" -Og thp; then
        TANG_URL="$(jose fmt -j "${CLEVIS_CONFIG}" -Og url -u-)"
        # Download advertisement.
        curl -o adv.jws "${TANG_URL}"/adv
        clevis_cfg="$(jose fmt -j "${clevis_cfg}" -q adv.jws -s adv -Uo-)"
        echo "clevis_cfg=${clevis_cfg}"
      fi
    fi

    # 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 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

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

    if [ "${CLEVIS_PIN}" = "tang" ]; then
      mkdir -p /etc/dracut.conf.d/
      echo 'kernel_cmdline="rd.neednet=1"' > /etc/dracut.conf.d/10mt-ks-post-clevis.conf
    fi

    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 "CLEVIS_PIN(${CLEVIS_PIN})"
    echo "CLEVIS_CONFIG(${CLEVIS_CONFIG})"
    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:

