Attempt to support backing up commands

This commit is contained in:
Torjus Håkestad 2025-01-27 22:34:13 +01:00
parent 162c35769c
commit 5b9b65bc1f
Signed by: torjus
SSH Key Fingerprint: SHA256:KjAds8wHfD2mBYK2H815s/+ABcSdcIHUndwHEdSxml4
2 changed files with 58 additions and 24 deletions

View File

@ -11,30 +11,7 @@ let
runtimeInputs = [
pkgs.restic
];
text = ''
if [ -z "$BACKUP_HELPER_DIRS" ]; then
echo "BACKUP_HELPER_DIRS is not set"
exit 1;
fi
exit_code=0;
for i in ''${BACKUP_HELPER_DIRS//,/ }; do
echo "Starting backup of $i";
if ! output=$(restic backup "$i"); then
exit_code=1;
echo "Backup of $i failed with exit code $?:"
echo "$output"
else
echo "Backup of $i successful:"
echo "$output"
fi
done
if [ "$BACKUP_FORGET" -eq 1 ]; then
echo "Removing old backups"
output=$(restic forget -d 7 -w 4 -m 6 --keep-within 1d --prune)
echo "$output"
fi
exit "$exit_code";
'';
text = (builtins.readFile ./backup.sh);
};
in
{
@ -50,6 +27,11 @@ in
default = [ ];
description = "Directories to be backed up.";
};
backup-commands = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "Backup the stdout of commands. Format strings like key:command";
};
schedule = lib.mkOption {
type = lib.types.str;
default = "*-*-* 00:00:00";
@ -83,6 +65,9 @@ in
}
// lib.attrsets.optionalAttrs (builtins.hasAttr "password-file" cfg) {
RESTIC_PASSWORD_FILE = cfg.password-file;
}
// lib.attrsets.optionalAttrs (cfg.backup-commands != [ ]) {
BACKUP_HELPER_COMMANDS = lib.strings.concatStringsSep ";" cfg.backup-commands;
};
serviceConfig = {
Type = "oneshot";

49
backup.sh Normal file
View File

@ -0,0 +1,49 @@
#!/usr/bin/env bash
# If neither of BACKUP_HELPER_DIRS and BACKUP_HELPER_COMMANDS not set. Exit
if [ -z "$BACKUP_HELPER_DIRS" ] && [ -z "$BACKUP_HELPER_COMMANDS" ]; then
echo "BACKUP_HELPER_DIRS is not set"
exit 1;
fi
exit_code=0;
# Backup directories
if [ -n "$BACKUP_HELPER_DIRS" ]; then
for i in ${BACKUP_HELPER_DIRS//,/ }; do
echo "Starting backup of $i";
if ! output=$(restic backup "$i"); then
exit_code=1;
echo "Backup of $i failed with exit code $?:"
echo "$output"
else
echo "Backup of $i successful:"
echo "$output"
fi
done
fi
# Backup command outputs
if [ -n "$BACKUP_HELPER_COMMANDS" ]; then
IFS=";" read -r -a pairs <<< "$BACKUP_HELPER_COMMANDS"
for pair in "${pairs[@]}"; do
IFS=":" read -r key value <<< "$pair"
if ! output=$(restic backup --stdin-filename "$key" --stdin-from-command -- "$value"); then
exit_code=1;
echo "Backup of $i failed with exit code $?:"
echo "$output"
else
echo "Backup of $i successful:"
echo "$output"
fi
done
fi
if [ "$BACKUP_FORGET" -eq 1 ]; then
echo "Removing old backups"
output=$(restic forget -d 7 -w 4 -m 6 --keep-within 1d --prune)
echo "$output"
fi
exit "$exit_code"