Files
noofac-snackpot/templates/docker-compose/borgmatic/backup.sh
2023-04-12 20:20:34 +01:00

77 lines
1.6 KiB
Bash
Executable File

#!/bin/sh
# Run the backup and mail the logs
# Set TEST_SMTP=1 to run in SMTP testing mode, which will just send an email
set -o pipefail
# Set up environment
/bin/sh /scripts/msmtprc.sh
/bin/sh /scripts/env.sh
BACKUP_COMMAND="borgmatic --stats -v 2"
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?="
# Helper function to prepend a timestamp and the first parameter to every line of STDIN
_indent() {
while read -rs line; do
printf "%s%s\n" "$(date +%s)" "$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
{
"$@" 2>&1 1>&3 3>&- | _indent " ! "
} 3>&1 1>&2 | _indent " | " >>"$LOGFILE"
}
report() {
if [ -n "$SUCCESS" ]; then
log echo SUCCESS
PREFIX="$SUCCESS_PREFIX"
else
log echo FAILED
PREFIX="$FAILED_PREFIX"
fi
printf "Subject: $PREFIX: $MAIL_SUBJECT\n\n$(cat $LOGFILE)\n" |
sendmail -t "$MAIL_TO"
}
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 "Done, removing $LOGFILE"
rm -f "$LOGFILE"
}
# Handle various kinds of exit
trap failed INT QUIT KILL
trap cleanup EXIT
if [ -n "$TEST_SMTP" ]; then
echo "Testing mail to $MAIL_TO"
testmail
echo "Done."
exit
fi
echo "STARTED" >> "$LOGFILE"
if log $BACKUP_COMMAND; then
SUCCESS=1
report
fi