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

#######################################
# Append the GRUB superuser block to '/etc/grub.d/40_custom'.
# Globals:
#   DIR_CNF
#   TARGET
# Arguments:
#   None
# Returns:
#   0: on success
#   ERR_READ_GRUB_FILE
#######################################
update_grub_password() {
  ### Declare Arrays, HashMaps, and Variables.
  declare var_username="superadmin" var_password="" var_password_file="${DIR_CNF}/password_grub.txt" \
          var_of="${TARGET}/etc/grub.d/40_custom" var_grub_entry=""

  ### TODO: PASSWORD REMINDER
  ### No tracing for security reasons
  #[[ "${VAR_DEBUG_TRACE,,}" == "true" ]] && set +x

  var_password=$(<"${var_password_file}") || return "${ERR_READ_GRUB_FILE}"

  var_grub_entry=$(generate_grub_password_pbkdf2 "${var_username}" "${var_password}")

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

  ### Append if not already present
  if ! grep -q "set superusers=" "${var_of}"; then
    {
      echo ""
      echo "### Added by CISS.debian.installer ###"
      echo "${var_grub_entry}"
      echo "### End by CISS.debian.installer ###"
    } >> "${var_of}"
  fi

  do_in_target "${TARGET}" update-grub

  guard_dir && return 0
}

#######################################
# Generate PBKDF2 password hash for GRUB.
# Arguments:
#   1: Username (default to superadmin).
#   2: User password.
# Returns:
#   0: on success
#######################################
generate_grub_password_pbkdf2() {
  declare var_user="${1:-superadmin}"
  declare var_pass="${2:?error: password required}"

  expect <<EOF
    log_user 0
    spawn grub-mkpasswd-pbkdf2 --iteration-count=131072 --salt=64 --buflen=64
    expect "Enter password:"
    send "${var_pass}\r"
    expect "Reenter password:"
    send "${var_pass}\r"
    expect {
      -re {PBKDF2 hash of your password is (\S+)} {
        puts "set superusers=\"${var_user}\"\npassword_pbkdf2 ${var_user} \$expect_out(1,string)"
      }
    }
EOF

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