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

#######################################
# Generates salt.
# Globals:
#   ERR_GENERATE_SALT
#   NL
# Arguments:
#   None
# Returns:
#   0: on success
#   ERR_GENERATE_SALT
#######################################
generate_salt() {
  declare var_salt=""
  while :; do
    # shellcheck disable=SC2312
    var_salt=$(head -c 12 /dev/random | base64 | tr -dc 'A-Za-z0-9' | head -c 16) || return "${ERR_GENERATE_SALT}"
    [[ ${#var_salt} -eq 16 ]] && break
  done
  printf '%s%b' "${var_salt}" "${NL}"
  return 0
}

#######################################
# Reads and validates a secure one-line password file.
# Globals:
#   ERR_READ_PASS_FILE
#   VAR_DEBUG_TRACE
# Arguments:
#   1: Path to password file
#   2: Name of target variable (via nameref)
# Returns:
#   0: on success
#   ERR_READ_PASS_FILE
#######################################
read_password_file() {
  declare -r var_input_file="${1}"
  declare -n var_output_file="${2}"
  declare -a lines=()

  ### TODO: PASSWORD REMINDER
  ### No tracing for security reasons
  [[ "${VAR_DEBUG_TRACE,,}" == "true" ]] && set +x
  if [[ ! -f "${var_input_file}" ]]; then
    do_log "fatal" "file_only" "0104() Password file '${var_input_file}' not found."
    return "${ERR_READ_PASS_FILE}"
  fi

  mapfile -t lines < "${var_input_file}"

  if (( ${#lines[@]} != 1 )); then
    do_log "fatal" "file_only" "0104() Password file '${var_input_file}' MUST contain exactly one line."
    return "${ERR_READ_PASS_FILE}"
  fi

  var_output_file="${lines[0]}"
  ### Trim leading and trailing whitespace.
  var_output_file="${var_output_file#"${var_output_file%%[![:space:]]*}"}" ### leading
  var_output_file="${var_output_file%"${var_output_file##*[![:space:]]}"}" ### trailing

  if [[ -z "${var_output_file}" ]]; then
    do_log "fatal" "file_only" "0104() Password file '${var_input_file}' contains only whitespace."
    return "${ERR_READ_PASS_FILE}"
  fi

  ### Turn on tracing again
  [[ "${VAR_DEBUG_TRACE,,}" == "true" ]] && set -x
  ### TODO: PASSWORD REMINDER

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