arch-installer/lib/util.sh
Daniel Langbein bce90bf7d8 v3.0
mkinitcpio or dracut for initramfs generation
2023-03-22 20:18:08 +01:00

105 lines
2.9 KiB
Bash

function join_by() {
# Join array elements with character $1
#
# arg $1: A single-character delimiter, e.g. ','
# arg $2: Name of source array
# arg $3: Variable name to store result
validate_args 3 "$@" || return $?
local delimiter="${1}"
local -n source_array_ptr=$2
local -n joined_ptr=$3
# https://stackoverflow.com/a/2317171
joined_ptr=$(printf "${delimiter}%s" "${source_array_ptr[@]}") || return $?
joined_ptr=${joined_ptr:1} || return $?
}
function newline_to_space() {
# Replaces all newlines with spaces
#
# arg $1: Name of variable
validate_args 1 "$@" || return $?
local -n ptr=$1
# Replace newlines with spaces.
# See bash string substitution: https://gist.github.com/JPvRiel/b279524d3e56229a896477cb8082a72b
ptr="${ptr//$'\n'/' '}"
}
function newline_separated_to_array() {
# Watch out for tailing newlines as these result in additional elements "" at the end of the array.
# $1 and $2 can be equal (if the result shall be written to the input variable).
#
# arg $1: Name of variable with newline separated list
# arg $2: Name of array to store values into
validate_args 2 "$@" || return $?
local -n source_ptr=$1
local -n array1_ptr=$2
# source_ptr is a newline separated list.
# Store this as array array1_ptr.
# shellcheck disable=SC2034
readarray -t array1_ptr <<<"${source_ptr}"
}
function space_separated_to_array() {
# arg $1: Name of variable with space separated list
# arg $2: Name of array to store values into
validate_args 2 "$@" || return $?
local -n source_ptr=$1
# shellcheck disable=SC2178
local -n array2_ptr=$2
# source_ptr space separated list.
# Store this as array array2_ptr.
# Without newline at last array element: https://unix.stackexchange.com/a/519917/315162
# shellcheck disable=SC2034
readarray -d ' ' -t array2_ptr < <(printf '%s' "${source_ptr}")
}
function get_cpu_vendor() {
# If $1 does already contain a known CPU vendor, nothing is done.
#
# Otherwise, we try to detect the CPU vendor and save it into $1.
#
# arg $1: Name of variable to store CPU vendor into.
#
# @pre
# $1 ("amd", "intel", "none", *)
# @post
# $1 ("amd", "intel", "none")
validate_args 1 "$@" || return $?
local -n cpu_vendor_ptr=$1
# Check if variable does already contain known CPU vendor.
case "${cpu_vendor_ptr}" in
amd|intel|none)
return 0
;;
*)
:
;;
esac
# If in virtual environment (e.g. VirtualBox), then no CPU microcode is required.
if grep --quiet '^flags.*hypervisor' /proc/cpuinfo; then
echo 'Detected virtual environment.'
cpu_vendor_ptr='none'
return 0
fi
local vendor_id
vendor_id="$(grep vendor_id /proc/cpuinfo | head -1 | sed 's|vendor_id\s*:\s*||')"
if [ "${vendor_id}" = 'AuthenticAMD' ]; then
cpu_vendor_ptr='amd'
return 0
elif [ "${vendor_id}" = 'GenuineIntel' ]; then
cpu_vendor_ptr='intel'
return 0
else
echo 'Unknown CPU vendor'
return 1
fi
}