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

### Options in "GRUB_CMDLINE_LINUX" are always effective.
### Options in "GRUB_CMDLINE_LINUX_DEFAULT" are effective ONLY during normal boot (NOT during recovery mode).

guard_sourcing

#######################################
# Hardening Grub boot parameter.
# Globals:
#   ARY_BOOTPARAM
#   TARGET
#   VAR_GRUB_CMDLINE_LINUX
#   VAR_GRUB_CMDLINE_LINUX_DEFAULT
#   VAR_NUKE
#   VAR_NUKE_HASH
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
update_grub_bootparameter() {
  ### Declare Arrays, HashMaps, and Variables.
  declare     var_nuke_string="" var_param="" var_label=""

  grub_extract_current_string

  # shellcheck disable=SC2034
  for var_param in "${ARY_BOOTPARAM[@]}"; do

    if [[ -z "${var_param}" ]]; then
      do_log "warn" "file_only" "4250() Empty GRUB parameter detected and skipped."
      continue
    fi

    if grep -qF -- "${var_param}" <<< "${VV_GRUB_CMDLINE_LINUX_DEFAULT}"; then
      do_log "info" "file_only" "4250() Skipping duplicate kernel parameter: '${var_param}'."
      continue
    fi

    VV_GRUB_CMDLINE_LINUX_DEFAULT="${VV_GRUB_CMDLINE_LINUX_DEFAULT} ${var_param}"

  done


  if [[ "${VAR_DROPBEAR}" == "true" ]]; then
    var_label="${HMP_PATH_ENCLABEL["/"]}"
    VV_GRUB_CMDLINE_LINUX="${VV_GRUB_CMDLINE_LINUX:+${VV_GRUB_CMDLINE_LINUX} }cryptdevice=${VAR_CRYPT_ROOT}:cryptroot root=/dev/mapper/${var_label}"
  fi

  if [[ "${VAR_NUKE}" == "true" ]]; then
    var_nuke_string="nuke=${VAR_NUKE_HASH}"
    # shellcheck disable=SC2034
    VV_GRUB_CMDLINE_LINUX="${VV_GRUB_CMDLINE_LINUX} ${var_nuke_string}"
  fi

  grub_finalize_string

  do_in_target "${TARGET}" update-grub

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