#!/bin/bash

# SPDX-License_identifier: BSD-3-Clause
# Script to check the last known date of the backup and warn if too old
# Requires jq and yq

set -e
set -o nounset
set -o pipefail

mailto="root"
fromname="yournamehere"
mailfrom="yournamehere <yourmail>"

max_days=7

last_bak=$(borgmatic list --last 1 --format "{end} {NEWLINE}" --successful --json | \
           jq '.[].archives | sort_by(.end)[].end | gsub("\\.000000$"; "Z") | fromdate')

repository_name=$(yq -r '.location.repositories[0]' /etc/borgmatic/config.yaml)

current=$(date +%s)
difference="$(( current - last_bak ))"
diff_days="$(( difference / (3600 * 24) ))"
host_name=$(hostname)

if (( diff_days > max_days ));
then
sendmail "$mailto" <<EOF
From: $mailfrom
To: $fromname <$mailto>
Subject:[borgbackup] Warning: backup older than $diff_days days.

Hello,

This is an automated message sent from $host_name.

The backup in $repository_name has not been updated in more than $max_days
days. It is advisable to check for errors or disabled services.

--
Automated report system

EOF
fi