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

#######################################
# Install microcode updates depending on architecture (amd64, arm64, intel64) and environment (Baremetal, VM).
# Globals:
#   TARGET
# Arguments:
#   None
# Returns:
#   0: on success
#######################################
installation_microcode() {
  declare var_microcode_pkgs=""

  declare var_whereiam; var_whereiam=$(virt-what | head -n1)
  [[ -z "${var_whereiam}" ]] && var_whereiam="baremetal"

  declare var_cpu_vendor; var_cpu_vendor=$(lscpu | awk -F: '/Vendor ID/ {print $2}' | xargs)

  case "${var_cpu_vendor}" in
    *AuthenticAMD*)   var_microcode_pkgs="amd64-microcode" ;;
    *GenuineIntel*)   var_microcode_pkgs="intel-microcode" ;;
    ""|*ARM*|*arm*|*) var_microcode_pkgs=""; do_log "info" "true" "ARM or unknown CPU detected – skipping microcode install" ;;
  esac

  ###########################################################################################
  # Generally, it is best to let the hypervisor handle CPU microcode updates.               #
  ###########################################################################################
  if [[ "${var_whereiam}" != "kvm" && -n "${var_microcode_pkgs}" ]]; then

    if ! do_in_target_script "${TARGET}" "dpkg -l ${var_microcode_pkgs} >/dev/null 2>&1"; then
      do_in_target "${TARGET}" apt-get install -y "${var_microcode_pkgs}"
    fi

  else

    do_log "info" "true" "Skipping microcode install (${var_whereiam}, ${var_microcode_pkgs:-none})"

  fi

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