ntfy_scripts/borg_HOSTNAME.sh

77 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
### I lost the link where I copied this script from, sorry, i'll update as soon as I find it back!
## This scripts checks for the last succesful BORG backups of a HOST, and alerts ntfy in case no succesful backup has been created for the last X days
backup_host="HOST_NAME"
n_days=3 # if backup was less recent than n_days, alert administrator
topicurl=https://NTFY_SERVER_IP/borg_alerts
make_it_fail=0 # set to 1 to test your alerts by simulating an old backup
export BORG_REPO=/mnt/BORG/$backup_host # point to your borg repo
export BORG_REMOTE_PATH=/usr/bin/borg # point to your borg executable
#export BORG_PASSPHRASE='redacted'
die()
{
echo "Error fetching or calculating date"
curl -k --retry 3 \
-d "Error fetching or calculating date" \
-H "Title: Borg on $backup_host" \
-H "Priority: high" \
-H "Tags: warning,boar" \
$topicurl
exit 1
}
is_num() # returns (exits) 0 if passed a valid integer
{
if (( $1 == $1 )) 2>/dev/null; then
return 0
else
return 1
fi
}
last=`borg list --last 10 --format "{archive} {end} {NEWLINE}" | grep --invert-match checkpoint | tail -1` # get the last 10 backups from the repo, filter out checkpoints, get last one
if (( $make_it_fail )); then
last="qwho-1989-05-08T11:11:11 Thu, 1989-05-08 11:11:11" # simulate an old backup
fi
echo Last backup: $last
last_date=$( echo $last | cut -d " " -f 3 )
if [[ -z $last_date ]]; then
die # didn't get a string
fi
last_timestamp=$( date --date=$last_date +%s 2>/dev/null )
now_timestamp=$( date +%s )
if ! ( ( is_num $last_timestamp ) && ( is_num $now_timestamp ) ); then
die # invalid timestamp
fi
days_ago=$( echo "($now_timestamp - $last_timestamp) / (3600 * 24)" | bc )
if ! ( ( is_num $days_ago ) && (( $days_ago >= 0 )) ); then
die # invalid or negative result
fi
# Sums successful - check backup time and send appropriate ntfy alert
if (( $days_ago < $n_days )); then
echo Good - last backup was $days_ago days ago - less than the $n_days day limit
echo Not sending alert to ntfy server...
else
echo Bad - last backup was $days_ago days ago - greater than the $n_days day limit
echo Sending alert...
curl -k --retry 3 \
-d "Bad - last backup was $days_ago days ago - greater than the $n_days day limit" \
-H "Title: Borg on $backup_host" \
-H "Priority: high" \
-H "Tags: warning,boar" \
$topicurl
fi