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

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

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

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

  if [ -z "${skip}" ]; then
    # Download advertisement.
    curl -o adv.jws "${TANG_SERVER}"/adv
    clevis_cfg="$(printf '{"url":"%s","adv":"adv.jws"}' "${TANG_SERVER}")"
    echo "clevis_cfg=${clevis_cfg}"

    # 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 "TANG_SERVER(${TANG_SERVER})"
    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:

