homelab/_lib.sh

85 lines
1.9 KiB
Bash
Raw Normal View History

2022-12-31 14:19:03 +01:00
#!/bin/bash
# Useful functions for all scripts
set -euo pipefail
_err() {
echo "ERR: $@";
exit 1;
}
# Shortcut for mktemp
_mktmp() {
mktemp -p "$HL_TMP_DIR" $@;
}
# Substitute env variables in a file using python template strings
# all env vars must be prefixed with "HL_", and are case insensitive
# Ex:
# -- file.txt
# hello $person
#
# -- script.sh
# export HL_PERSON="world";
# cat $(_fill file.txt)
#
# Output: "hello world"
_fill() {
OUT="$(_mktmp)"
python3 - $1 > "$OUT" <<EOF
import os
import sys
from string import Template
from pathlib import Path
file = Path(sys.argv[1]).read_text()
mapping = {k[3:].lower(): v for k, v in os.environ.items() if k.startswith("HL_")}
sys.stdout.write(Template(file).substitute(mapping))
sys.stdout.flush()
EOF
echo "$OUT"
}
# Decrypt a file
_decrypt() {
OUT="$(_mktmp)"
age --decrypt --identity "$HL_AGE_IDENTITY" --output "$OUT" "$1"
echo "$OUT"
}
# Encrypt a file
_encrypt() {
OUT="$(_mktmp)"
PUB=`ssh-keygen -y -f "$HL_AGE_IDENTITY"`
age --encrypt --recipient "$PUB" --armor --output "$OUT" "$1"
echo "$OUT"
}
# Checks if all env vars are filled
_assert_vars() {
for var in "$@"; do
if ! [ -v $var ]; then
_err "$var is not set";
fi;
done;
}
# Run a checkpointed script. In it should only be functions
# beginning with "_ch_". These will get run in alphabetical order.
_run_checkpoints() {
FUNCS="$(declare -F | awk '{ print $3 }' | grep -E '^_ch_' | sort)";
touch run.checkpoints;
for f in $FUNCS; do
pushd "$(pwd)" > /dev/null;
if grep -q -E "^$f$" run.checkpoints; then
echo "skipping $f, already run";
popd > /dev/null;
else
echo "running $f";
$f
popd > /dev/null;
echo "$f" >> run.checkpoints;
fi;
done;
}
_assert_vars HL_TMP_DIR