#!/bin/bash
# SPDX-Version: 3.0
# SPDX-CreationInfo: 2025-05-05; WEIDNER, Marc S.; <msw@coresecret.dev>
# SPDX-ExternalRef: GIT https://git.coresecret.dev/msw/CISS.debian.live.builder.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.live.builder
# SPDX-Security-Contact: security@coresecret.eu

guard_sourcing

#######################################
# Kernel Image Selector
# Globals:
#   VAR_ARCHITECTURE
#   VAR_KERNEL
#   VAR_KERNEL_SRT
#   VAR_KERNEL_TMP
# Arguments:
#  None
# Returns:
#   42: Sorting Error.
#######################################
check_kernel() {
  clear
  declare -i counter=1
  declare first_string=""
  declare line=""
  declare -gx VAR_KERNEL=""
  declare name=""
  declare options=""

  if [[ ${VAR_ARCHITECTURE} != arm64 ]]; then
    apt-cache search linux-image | grep linux-image | grep amd64 | grep -v "meta-package" | grep -v "dbg" | grep -v "template" >> "${VAR_KERNEL_TMP}"
  else
    apt-cache search linux-image | grep linux-image | grep arm64 | grep -v "meta-package" | grep -v "dbg" | grep -v "template" >> "${VAR_KERNEL_TMP}"
  fi

  sort --output="${VAR_KERNEL_SRT}" "${VAR_KERNEL_TMP}" || {
    printf "❌ Error check_kernel() Line 40 sort failed\n" >&2
    # shellcheck disable=SC2162
    read -p  $'\e[92m✅ Press \'ENTER\' to exit the script ... \e[0m'
    return 42
  }

    while IFS= read -r line; do
      first_string=${line%% *}
      name=${first_string#linux-image-}
      options+=("${name}" "${counter}" off)
      ((counter++))
    done < "${VAR_KERNEL_SRT}"

  # shellcheck disable=SC2155
  if declare -gx VAR_KERNEL=$(dialog \
                          --no-collapse \
                          --ascii-lines \
                          --clear \
                          --backtitle "CISS.debian.live.builder" \
                          --title "Select the Kernel for the CISS Hardened Debian Live Image ISO" \
                          --radiolist "Kernel available \n *+bpo*       : Debian Backported Kernel \n *cloud*      : Special lightweight images for KVM \n *unsigned*   : Unsigned Kernel \n *preempt_rt* : Special Kernel for real-time-computing \n Not unsigned marked are MS signed Kernel for Secure Boot \n" 0 0 "${options[@]}" 3>&1 1>&2 2>&3 3>&-); then
    clear
  else
    clear
    if [[ "${VAR_ARCHITECTURE}" == "amd64" ]]; then
      declare -gx VAR_KERNEL="amd64"
    elif [[ "${VAR_ARCHITECTURE}" == "arm64" ]]; then
      declare -gx VAR_KERNEL="arm64"
    fi
  fi
}
# vim: number et ts=2 sw=2 sts=2 ai tw=128 ft=sh
