#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-06-17; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.installer.git
# SPDX-FileContributor: WEIDNER, Marc S.; Centurion Intelligence Consulting Agency
# SPDX-FileCopyrightText: 2024-2025; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-FileType: SOURCE
# SPDX-License-Identifier: EUPL-1.2 OR LicenseRef-CCLA-1.0
# SPDX-LicenseComment: This file is part of the CISS.debian.installer.secure framework.
# SPDX-PackageName: CISS.debian.installer
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Benchmark cryptsetup KDF to determine pbkdf-memory and pbkdf-force-iterations for given pbkdf-threads.
# Globals:
#   VAR_ITER_TIME
#   VAR_KDF_ITERATIONS
#   VAR_KDF_MEMORY
#   VAR_KDF_THREADS
#   VAR_RECIPE_STRING
#   VAR_SETUP_PART
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
benchmarking_encryption() {
  declare var_result=""
  # shellcheck disable=SC2155
  declare -girx VAR_KDF_THREADS=$(yq_val ".recipe.${VAR_RECIPE_STRING}.control.kdf.threads" "${VAR_SETUP_PART}")
  # shellcheck disable=SC2155
  declare -girx VAR_ITER_TIME=$(yq_val ".recipe.${VAR_RECIPE_STRING}.control.kdf.time"      "${VAR_SETUP_PART}")

  echo "BENCHMARK CRYPTSETUP ARGON2ID KDF PARAMETER ..."
  sync

  echo "BENCHMARK CRYPTSETUP ARGON2ID KDF PARAMETER - DROPPING PAGES ..."
  echo 3 >| /proc/sys/vm/drop_caches

  # shellcheck disable=SC2312
  var_result=$(cryptsetup benchmark --pbkdf argon2id --iter-time "${VAR_ITER_TIME:-3000}" --pbkdf-parallel "${VAR_KDF_THREADS:-1}" 2>/dev/null \
    | grep -E '^argon2id[[:space:]]+[0-9]+[[:space:]]+iterations')

  echo "${var_result}"

  do_log "info" "file_only" "3210() [cryptsetup benchmark --pbkdf argon2id --iter-time ${VAR_ITER_TIME:-3000} --pbkdf-parallel ${VAR_KDF_THREADS:-1}]."
  do_log "info" "file_only" "3210() Results: [${var_result}]."

  # shellcheck disable=SC2155
  declare -girx VAR_KDF_ITERATIONS=$(awk '{print $2}' <<<"${var_result}")
  # shellcheck disable=SC2155
  declare -girx VAR_KDF_MEMORY=$(awk -F'[ ,]+' '{print $4}' <<<"${var_result}")

  guard_dir && return 0
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
