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

#######################################
# Reading and extracting variables from "${PRESEED}".
# Globals:
#   ERR_NO_VALID_RECIPE
#   HMP_RECIPE_DEV_PARTITIONS
#   VAR_PRESEED
#   VAR_RECIPE_DEV_COUNTER
#   VAR_RECIPE_FIRMWARE
#   VAR_RECIPE_STRING
#   VAR_RECIPE_TABLE
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
yaml_reader() {
  ### Declare and substitute input files
  declare -r var_if="${VAR_PRESEED}"
  ### Search pattern for variables (recipe_<string>_active='true')
  declare -r var_search_pattern="^recipe_.*_active='true'"

  declare var_line=""
  declare var_middle_part=""
  ### Read "${var_if}" line by line
  while IFS= read -r var_line; do
    ### Check, if line matches the search pattern
    if [[ "${var_line}" =~ ${var_search_pattern} ]]; then
      ### Extract the middle part or second position
      var_middle_part=$(echo "${var_line}" | sed -E "s/^recipe_([^_]+)_active='true'/\1/")
      declare -gx VAR_RECIPE_STRING="${var_middle_part}"
      ### Exit after first occurrence
      break
    fi
  done < "${var_if}"

  if [[ -n ${VAR_RECIPE_STRING} ]]; then
    do_log "info" "false" "Found active recipe string: '${VAR_RECIPE_STRING}'."
  else
    do_log "fatal" "false" "Found NO active recipe string: '${VAR_RECIPE_STRING}'." >&2
    exit "${ERR_NO_VALID_RECIPE}"
  fi

  ### Variable for highest device count e.g., /dev/sdf = "f"
  declare var_highest_dev

  ### Search "${var_if}" for matching recipe_${VAR_RECIPE_STRING}_dev_* entries and find the highest dev letter
  var_highest_dev=$(grep -E "^recipe_${VAR_RECIPE_STRING}_dev_" "${var_if}" | awk -F'_' '
{
  if (NF >= 4) {
    ### Extract 4th position (e.g., "recipe_${VAR_RECIPE_STRING}_dev_sda" or "recipe_${VAR_RECIPE_STRING}_dev_vda")
    device_field = $4
    ### Check, if field is at least 3 char wide and last char contains a letter
    if (length(device_field) >= 3) {
      last_char = substr(device_field, length(device_field), 1)  ### Extract last letter of respective field
      if (last_char ~ /^[a-z]$/ && last_char > max) {
        max = last_char
      }
    }
  }
}
END { print max }
')

  ### Save the result in VAR_RECIPE_DEV_COUNTER
  declare -gx VAR_RECIPE_DEV_COUNTER="${var_highest_dev}"

  if [[ -n ${VAR_RECIPE_DEV_COUNTER} ]]; then
    do_log "info" "false" "Found highest recipe device: '${VAR_RECIPE_DEV_COUNTER}'."
  else
    do_log "fatal" "false" "Found NO highest recipe device: '${VAR_RECIPE_DEV_COUNTER}'." >&2
    exit "${ERR_NO_VALID_RECIPE}"
  fi

  declare var_device="" var_fields="" var_line="" var_partition=""
  declare -Agx HMP_RECIPE_DEV_PARTITIONS=()

  ### Read var_if and iterate through all matching entries without executing in a subshell
  while read -r var_line; do
    ### Extract fields of line
    IFS='_' read -ra var_fields <<< "${var_line}"

    ### Check that enough fields are available
    if [[ "${#var_fields[@]}" -ge 5 ]]; then
      var_device="${var_fields[3]}"    ### The fourth position includes the device (e.g., sda, vda, xvda)
      var_partition="${var_fields[4]}" ### The fifth position includes the partition (e.g., 13)

      ### Check, if the partition is a number and higher than the current value
      if [[ "${var_partition}" =~ ^[0-9]+$ ]]; then

        if [[ -z "${HMP_RECIPE_DEV_PARTITIONS[${var_device}]}" || "${var_partition}" -gt ${HMP_RECIPE_DEV_PARTITIONS[${var_device}]} ]]; then
          # shellcheck disable=SC2004
          HMP_RECIPE_DEV_PARTITIONS[${var_device}]="${var_partition}"
        fi

      fi

    fi
  done < <(grep -E "^recipe_${VAR_RECIPE_STRING}_dev_" "${var_if}")

  for var_device in "${!HMP_RECIPE_DEV_PARTITIONS[@]}"; do
    do_log "info" "false" "Highest number of partitions for ${var_device}: ${HMP_RECIPE_DEV_PARTITIONS[${var_device}]}"
  done

  ### Extract chosen partition table
  declare recipe_table_var="recipe_${VAR_RECIPE_STRING}_control_table"
  declare -gx VAR_RECIPE_TABLE="${!recipe_table_var}"

  ### Extract chosen firmware
  declare recipe_firmware_var="recipe_${VAR_RECIPE_STRING}_control_firmware"
  declare -gx VAR_RECIPE_FIRMWARE="${!recipe_firmware_var}"

  if [[ "${VAR_RECIPE_TABLE,,}" == "gpt" && "${VAR_RECIPE_FIRMWARE,,}" == "uefi" ]]; then

    do_log "info" "false" "Partition table: '${VAR_RECIPE_TABLE}' and firmware: '${VAR_RECIPE_FIRMWARE}' > ESP 'EF00' necessary."

  elif [[ "${VAR_RECIPE_TABLE,,}" == "gpt" && "${VAR_RECIPE_FIRMWARE,,}" == "bios" ]]; then

    do_log "info" "false" "Partition table: '${VAR_RECIPE_TABLE}' and firmware: '${VAR_RECIPE_FIRMWARE}' > BIOS Boot Partition 'EF02' necessary."

  elif [[ "${VAR_RECIPE_TABLE,,}" == "msdos" && "${VAR_RECIPE_FIRMWARE,,}" == "uefi" ]]; then

    do_log "info" "false" "Partition table: '${VAR_RECIPE_TABLE}' and firmware: '${VAR_RECIPE_FIRMWARE}' > ESP on MBR needs partition type '0xEF'."

  elif [[ "${VAR_RECIPE_TABLE,,}" == "msdos" && "${VAR_RECIPE_FIRMWARE,,}" == "bios" ]]; then

    do_log "info" "false" "Partition table: '${VAR_RECIPE_TABLE}' and firmware: '${VAR_RECIPE_FIRMWARE}' > No special firmware partition necessary."

  fi

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