Introduce installSecretFn script function to make script shorter.

This commit is contained in:
Félinàun Chapeau 2023-12-11 17:22:02 +01:00
parent 417caa847f
commit c71f8f5cde

View file

@ -61,9 +61,19 @@ with lib; let
} }
''; '';
installSecret = secretType: '' installSecretFn = ''
${setTruePath secretType} installSecret() {
echo "decrypting '${secretType.file}' to '$_truePath'..." symlink="$1"
name="$2"
path="$3"
file="$4"
mode="$5"
if "$symlink"; then
_truePath="${cfg.secretsMountPoint}/$_agenix_generation/$name"
else
_truePath="$path"
fi
echo "decrypting $file to '$_truePath'..."
TMP_FILE="$_truePath.tmp" TMP_FILE="$_truePath.tmp"
IDENTITIES=() IDENTITIES=()
@ -77,19 +87,19 @@ with lib; let
test "''${#IDENTITIES[@]}" -eq 0 && echo "[agenix] WARNING: no readable identities found!" test "''${#IDENTITIES[@]}" -eq 0 && echo "[agenix] WARNING: no readable identities found!"
mkdir -p "$(dirname "$_truePath")" mkdir -p "$(dirname "$_truePath")"
[ "${secretType.path}" != "${cfg.secretsDir}/${secretType.name}" ] && mkdir -p "$(dirname "${secretType.path}")" [ "$path" != "${cfg.secretsDir}/$name" ] && mkdir -p "$(dirname "$path")"
( (
umask u=r,g=,o= umask u=r,g=,o=
test -f "${secretType.file}" || echo '[agenix] WARNING: encrypted file ${secretType.file} does not exist!' test -f "$file" || echo '[agenix] WARNING: encrypted file '$file' does not exist!'
test -d "$(dirname "$TMP_FILE")" || echo "[agenix] WARNING: $(dirname "$TMP_FILE") does not exist!" test -d "$(dirname "$TMP_FILE")" || echo "[agenix] WARNING: $(dirname "$TMP_FILE") does not exist!"
LANG=${config.i18n.defaultLocale or "C"} ${ageBin} --decrypt "''${IDENTITIES[@]}" -o "$TMP_FILE" "${secretType.file}" LANG=${config.i18n.defaultLocale or "C"} ${ageBin} --decrypt "''${IDENTITIES[@]}" -o "$TMP_FILE" "$file"
) )
chmod ${secretType.mode} "$TMP_FILE" chmod "$mode" "$TMP_FILE"
mv -f "$TMP_FILE" "$_truePath" mv -f "$TMP_FILE" "$_truePath"
${optionalString secretType.symlink '' "$symlink" && ([ "$path" != "${cfg.secretsDir}/$name" ] && ln -sfn "${cfg.secretsDir}/$name" "$path")
[ "${secretType.path}" != "${cfg.secretsDir}/${secretType.name}" ] && ln -sfn "${cfg.secretsDir}/${secretType.name}" "${secretType.path}" true
''} }
''; '';
testIdentities = testIdentities =
@ -111,10 +121,20 @@ with lib; let
} }
''; '';
installSecrets = builtins.concatStringsSep "\n" ( installSecrets = let
mkLine = secretType: ''
installSecret "${
if secretType.symlink
then "true"
else "false"
}" "${secretType.name}" "${secretType.path}" "${secretType.file}" "${secretType.mode}";
'';
in
builtins.concatStringsSep "\n" (
["echo '[agenix] decrypting secrets...'"] ["echo '[agenix] decrypting secrets...'"]
++ testIdentities ++ testIdentities
++ (map installSecret (builtins.attrValues cfg.secrets)) ++ [installSecretFn]
++ (map mkLine (builtins.attrValues cfg.secrets))
++ [cleanupAndLink] ++ [cleanupAndLink]
); );