diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2026-10-03 08:52:49 -0700 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2026-10-11 18:33:35 -0700 |
| commit | de40b1e69eaabac3ca01774fa3a4e7abc463ac7c (patch) | |
| tree | 9e6ba70dd1f982f851c84a1aa542c1a28a55010f /lib.sh | |
| parent | Add prompt to remove build directory if it exists (diff) | |
| download | site-server-images-de40b1e69eaabac3ca01774fa3a4e7abc463ac7c.zip | |
Customize the disk layout via disklabel templates
Diffstat (limited to 'lib.sh')
| -rw-r--r-- | lib.sh | 81 |
1 files changed, 81 insertions, 0 deletions
@@ -0,0 +1,81 @@ +#!/bin/sh +set -o nounset +set -o errexit + +# Get the number of cpus of the current system. +# +# STDOUT: +# The number of CPU cores +# +# RETURNS: +# 1 on failure +get_ncpus() { + _get_ncpus_os="$(uname -s)" + if [ "$_get_ncpus_os" = 'Darwin' ]; then + sysctl -n hw.ncpu + else + return 1 + fi +} + +# Get the total amount of memory on the current system. +# +# ARGS: +# $1 (Optional): The units to retrieve the memory size in. +# Options are: 'b', 'mb', 'kb', 'gb'. Defaults to 'b' (bytes). +# +# STDOUT: +# The total amount of memory. +# +# RETURNS: +# 1 on failure +get_memsize() { + _get_memsize_unit="${1:-b}" + _get_memsize_unit_spec="b mb kb gb" + if ! validate_enum "$_get_memsize_unit" "$_get_memsize_unit_spec"; then + echo "[ERROR] Expected one of: '$_get_memsize_unit_spec'. Got '$_get_memsize_unit'." >&2 + return 1 + fi + + _get_memsize_os="$(uname -s)" + if [ "$_get_memsize_os" = 'Darwin' ]; then + _get_memsize_mem=$(sysctl -n hw.memsize) + else + return 1 + fi + + case "$_get_memsize_unit" in + b) _get_memsize_divisor=1 ;; + kb) _get_memsize_divisor=1024 ;; + mb) _get_memsize_divisor=1048576 ;; + gb) _get_memsize_divisor=1073741824 ;; + esac + + echo $((_get_memsize_mem / _get_memsize_divisor)) +} + +validate_enum() { + _validate_enum_val=$1 + _validate_enum_spec=$2 + + set -f # Temporarily disable pathname expansion e.g. foo* + # See `set` in `man bash`: + # > Any arguments remaining after option + # > processing are treated as values for the positional parameters and + # > are assigned, in order, to $1, $2, ..., $n. + # shellcheck disable=SC2086 + set -- $_validate_enum_spec + set +f + + for item in "$@"; do + [ "$_validate_enum_val" = "$item" ] && return 0 + done + return 1 +} + +require_readable_file() { + if [ ! -f "$1" ] || [ ! -r "$1" ]; then + echo "File not found or not readable: $1" >&2 + exit 1 + fi +} |