Files
noofac-snackpot/templates/docker-compose/borgmatic/backup.sh
Nick Stokoe 5ca9ecfe2a templates/docker-compose/borgmatic/ - avoid losing STDERR lines
use stdbuf to change the buffereing mode to be linewise
2025-05-28 12:22:32 +01:00

102 lines
2.3 KiB
Bash
Executable File

#!/bin/sh
# Run the backup and mail the logs:
# Depending on parameter 1:
# - test-smtp: just send a test email to $MAIL_TO
# - run: create the backup, no checks
# - check: prune, compact and check the backup
# Anything else is an error.
set -o pipefail
# Set up environment
/bin/sh /scripts/msmtprc.sh
/bin/sh /scripts/env.sh
RUN_COMMAND="borgmatic --stats -v 2 create"
CHECK_COMMAND="borgmatic --stats -v 1 prune compact check"
LOGFILE="/tmp/backup_run_$(date +%s).log"
SUCCESS_PREFIX="=?utf-8?Q? =E2=9C=85 SUCCESS?="
FAILED_PREFIX="=?utf-8?Q? =E2=9D=8C FAILED?="
PARAM="$1"
# Helper function to prepend a timestamp and the first parameter to every line of STDIN
indent() {
while IFS='' read -rs line; do
echo "$(date -Iminutes)${1:- }$line"
done
}
# This function prepends timestamps to stderr and stdout of the
# command supplied as parameters to this.
log() {
# Adapted from https://stackoverflow.com/a/31151808
{
stdbuf -oL -eL "$@" 2>&1 1>&3 3>&- | indent " ! "
} 3>&1 1>&2 | indent " | " | tee -a "$LOGFILE"
}
report() {
if [ "$RESULT" = "0" ]; then
log echo "SUCCESS!"
PREFIX="$SUCCESS_PREFIX"
else
log echo "FAILED: $RESULT"
PREFIX="$FAILED_PREFIX"
fi
printf "Subject: %s: '%s'\n\n%s\n" "$PREFIX" "$PARAM" "$(cat $LOGFILE)" |
sendmail -t "$MAIL_TO"
log echo "Report sent."
}
testmail() {
echo -e "Subject: TESTING!\n\ntest mail, please ignore\n" |
sendmail -t "$MAIL_TO"
}
failed() {
log echo "Exited abnormally!"
report
rm -f "$LOGFILE"
}
cleanup() {
borgmatic break-lock
echo "Removing $LOGFILE"
rm -f "$LOGFILE"
echo "Exiting."
}
# Handle various kinds of exit
trap failed INT QUIT KILL
trap cleanup EXIT
case "$PARAM" in
test-smtp)
echo "Testing mail to $MAIL_TO"
testmail
echo "Done."
;;
check)
log echo STARTED: $CHECK_COMMAND
log $CHECK_COMMAND
RESULT=$?
report
;;
run)
log echo STARTED: $RUN_COMMAND
log $RUN_COMMAND
RESULT=$?
report
;;
dummy-run)
log echo STARTED: dummy-run
borgmatic nonesuch
RESULT=$?
report
;;
*)
log echo "UNKNOWN COMMAND: '$PARAM'"
report
;;
esac