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

### Variable to finish GRUB CMDLINE strings.
declare -grx VAR_H='"'

#######################################
# Helper module to extract the current GRUB CMDLINE strings.
# Globals:
#   TARGET
#   VAR_GRUB_CMDLINE_LINUX
#   VAR_GRUB_CMDLINE_LINUX_DEFAULT
#   VAR_ORIG_GRUB_CMDLINE_LINUX
#   VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT
# Arguments:
#   None
#######################################
old_grub_extract_current_string() {
  # shellcheck disable=SC2155
  declare -gx VAR_ORIG_GRUB_CMDLINE_LINUX=$(grep -E 'GRUB_CMDLINE_LINUX=' "${TARGET}/etc/default/grub")
  # shellcheck disable=SC2155
  declare -gx VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT=$(grep -E 'GRUB_CMDLINE_LINUX_DEFAULT=' "${TARGET}/etc/default/grub")
  # shellcheck disable=SC2155
  declare -gx VAR_GRUB_CMDLINE_LINUX=$(grep -E 'GRUB_CMDLINE_LINUX=' "${TARGET}/etc/default/grub" | sed 's/.$//')
  # shellcheck disable=SC2155
  declare -gx VAR_GRUB_CMDLINE_LINUX_DEFAULT=$(grep -E 'GRUB_CMDLINE_LINUX_DEFAULT=' "${TARGET}/etc/default/grub" | sed 's/.$//')
}

#######################################
# description
# Globals:
#   TARGET
#   VAR_ORIG_GRUB_CMDLINE_LINUX
#   VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT
#   VK_GRUB_CMDLINE_LINUX
#   VK_GRUB_CMDLINE_LINUX_DEFAULT
#   VV_GRUB_CMDLINE_LINUX
#   VV_GRUB_CMDLINE_LINUX_DEFAULT
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
grub_extract_current_string() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -gx VAR_ORIG_GRUB_CMDLINE_LINUX="" VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT="" \
    VK_GRUB_CMDLINE_LINUX='' VK_GRUB_CMDLINE_LINUX_DEFAULT='' \
    VV_GRUB_CMDLINE_LINUX="" VV_GRUB_CMDLINE_LINUX_DEFAULT=""
  declare     vv_raw_lin="" vv_raw_lin_def=""

  ### Original lines (retained, strictly anchored).
  VAR_ORIG_GRUB_CMDLINE_LINUX=$(grep -E '^GRUB_CMDLINE_LINUX=' "${TARGET}/etc/default/grub")
  VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT=$(grep -E '^GRUB_CMDLINE_LINUX_DEFAULT=' "${TARGET}/etc/default/grub")

  ### Keys (fixed prefixes).
  VK_GRUB_CMDLINE_LINUX='GRUB_CMDLINE_LINUX='
  VK_GRUB_CMDLINE_LINUX_DEFAULT='GRUB_CMDLINE_LINUX_DEFAULT='

  ### Raw values (with quotes if necessary).
  # shellcheck disable=SC2295
  vv_raw_lin="${VAR_ORIG_GRUB_CMDLINE_LINUX#${VK_GRUB_CMDLINE_LINUX}}"
  # shellcheck disable=SC2295
  vv_raw_lin_def="${VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT#${VK_GRUB_CMDLINE_LINUX_DEFAULT}}"

  ### Remove outer quotes symmetrically.
  if [[ -n ${vv_raw_lin} ]]; then

    declare q="${vv_raw_lin:0:1}"

    if [[ ${q} == "'" || ${q} == '"' ]]; then

      [[ ${vv_raw_lin: -1} == "${q}" ]] && vv_raw_lin=${vv_raw_lin:1:-1} || vv_raw_lin=${vv_raw_lin:1}

    fi
  fi

  if [[ -n ${vv_raw_lin_def} ]]; then

    declare q="${vv_raw_lin_def:0:1}"

    if [[ ${q} == "'" || ${q} == '"' ]]; then

      [[ ${vv_raw_lin_def: -1} == "${q}" ]] && vv_raw_lin_def=${vv_raw_lin_def:1:-1} || vv_raw_lin_def=${vv_raw_lin_def:1}

    fi

  fi

  ### Trim leading and trailing whitespace (including TAB, CR, and LF).
  ### Front:  remove the longest prefix from whitespace.
  vv_raw_lin="${vv_raw_lin#"${vv_raw_lin%%[![:space:]]*}"}"
  vv_raw_lin_def="${vv_raw_lin_def#"${vv_raw_lin_def%%[![:space:]]*}"}"

  ### Rear: remove the longest suffix from whitespaces.
  vv_raw_lin="${vv_raw_lin%"${vv_raw_lin##*[![:space:]]}"}"
  vv_raw_lin_def="${vv_raw_lin_def%"${vv_raw_lin_def##*[![:space:]]}"}"

  ### Expose end values (only value, without quotes, trimmed)
  # shellcheck disable=SC2034
  VV_GRUB_CMDLINE_LINUX="${vv_raw_lin}"
  # shellcheck disable=SC2034
  VV_GRUB_CMDLINE_LINUX_DEFAULT="${vv_raw_lin_def}"

  return 0
}

#######################################
# description
# Globals:
#   TARGET
#   VAR_GRUB_CMDLINE_LINUX
#   VAR_GRUB_CMDLINE_LINUX_DEFAULT
#   VK_GRUB_CMDLINE_LINUX
#   VK_GRUB_CMDLINE_LINUX_DEFAULT
#   VV_GRUB_CMDLINE_LINUX
#   VV_GRUB_CMDLINE_LINUX_DEFAULT
# Arguments:
#  None
# Returns:
#   0 ...
#######################################
grub_finalize_string() {
  ### Declare Arrays, HashMaps, and Variables.
  declare -a  ary_lines=()
  declare     var_file="${TARGET}/etc/default/grub"
  declare     var_new_lin="${VK_GRUB_CMDLINE_LINUX}'${VV_GRUB_CMDLINE_LINUX}'"
  declare     var_new_lin_def="${VK_GRUB_CMDLINE_LINUX_DEFAULT}'${VV_GRUB_CMDLINE_LINUX_DEFAULT}'"
  declare -i  var_found_lin=0 var_found_lin_def=0 var_line=0 i=0

  mapfile -t ary_lines < "${var_file}"

  ### Replace lines strictly based on the key (including '=').
  for (( i=0; i<${#ary_lines[@]}; i++ )); do

    var_line=${ary_lines[i]}

    case "${var_line}" in

      "${VK_GRUB_CMDLINE_LINUX}"*)

        ary_lines[i]="${var_new_lin}"
        var_found_lin=1
        ;;

      "${VK_GRUB_CMDLINE_LINUX_DEFAULT}"*)

        ary_lines[i]="${var_new_lin_def}"
        var_found_lin_def=1
        ;;

    esac

  done

  ### If Key is missing in the file, add it at the end (robust against minimal templates).
  (( var_found_lin == 0 ))      && ary_lines+=("${var_new_lin}")
  (( var_found_lin_def == 0 ))  && ary_lines+=("${var_new_lin_def}")

  ### Write back (without sed/awk, only built-ins).
  {
    for var_line in "${ary_lines[@]}"; do
      printf '%s\n' "${var_line}"
    done
  } >| "${var_file}"

  ### For subsequent use, export the complete lines as well.
  declare -gx VAR_GRUB_CMDLINE_LINUX="${var_new_lin}"
  declare -gx VAR_GRUB_CMDLINE_LINUX_DEFAULT="${var_new_lin_def}"

  return 0
}


#######################################
# Helper module to finish the modified GRUB CMDLINE strings.
# Globals:
#   TARGET
#   VAR_GRUB_CMDLINE_LINUX
#   VAR_GRUB_CMDLINE_LINUX_DEFAULT
#   VAR_H
#   VAR_ORIG_GRUB_CMDLINE_LINUX
#   VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT
# Arguments:
#   None
#######################################
old_grub_finalize_string() {
  declare var_grub_cmdline_linux="" var_grub_cmdline_linux_default=""

  var_grub_cmdline_linux="${VAR_GRUB_CMDLINE_LINUX}${VAR_H}"
  var_grub_cmdline_linux_default="${VAR_GRUB_CMDLINE_LINUX_DEFAULT}${VAR_H}"

  VAR_GRUB_CMDLINE_LINUX=$(printf '%s' "${var_grub_cmdline_linux}" | sed -e 's/[\/&\$]/\\&/g' )
  VAR_GRUB_CMDLINE_LINUX_DEFAULT=$(printf '%s' "${var_grub_cmdline_linux_default}" | sed -e 's/[\/&\$]/\\&/g' )

  sed -i "s|${VAR_ORIG_GRUB_CMDLINE_LINUX}|${VAR_GRUB_CMDLINE_LINUX}|" "${TARGET}/etc/default/grub"
  sed -i "s|${VAR_ORIG_GRUB_CMDLINE_LINUX_DEFAULT}|${VAR_GRUB_CMDLINE_LINUX_DEFAULT}|" "${TARGET}/etc/default/grub"
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
