#!/bin/bash
# Fail loudly when the vaultwarden backup has gone stale.
#
# The backup job itself is only visible by reading a log file, which is how a
# nine-day outage went unnoticed. This runs from a systemd timer as root, and
# exits non-zero when the newest backup on the share is older than the
# threshold, so the failure shows up in "systemctl status" and the journal.
#
# It covers both ways the backup can stop: the job failing, and the job not
# running at all.

set -uo pipefail

THRESHOLD_DAYS=2
MNT="/mnt/netbackup-check"
SMB_HOST="192.168.123.2"
SMB_SHARE="NetBackup"
CRED="/root/.smbcredentials"
TAG="vaultwarden-backup-check"

note() { logger -t "$TAG" -- "$*"; echo "$*"; }

cleanup() {
    if mountpoint -q "$MNT"; then
        umount "$MNT" 2>/dev/null || true
    fi
    rmdir "$MNT" 2>/dev/null || true
}
trap cleanup EXIT

if [ ! -f "$CRED" ]; then
    note "STALE CHECK FAILED - credentials missing at ${CRED}"
    exit 2
fi

mkdir -p "$MNT"

# Read-only, and not a system mount, so an unreachable NAS cannot wedge the
# system. A failure to mount is reported as "cannot verify", not as "stale",
# because those mean different things.
if ! mount -t cifs "//${SMB_HOST}/${SMB_SHARE}" "$MNT" \
        -o "credentials=${CRED},ro,iocharset=utf8,vers=3.0" 2>/dev/null; then
    note "CANNOT VERIFY - could not mount //${SMB_HOST}/${SMB_SHARE} to check backup freshness"
    exit 2
fi

newest=$(find "$MNT/Vault" -maxdepth 1 -type f -name 'vaultwarden-*.db' -printf '%T@ %p\n' 2>/dev/null \
         | sort -rn | head -1 | cut -d' ' -f2-)

if [ -z "$newest" ]; then
    note "STALE - no vaultwarden backups found on the share at all"
    exit 1
fi

# Age in days, rounded down.
age_days=$(( ( $(date +%s) - $(stat -c %Y "$newest") ) / 86400 ))
newest_name=$(basename "$newest")

if [ "$age_days" -ge "$THRESHOLD_DAYS" ]; then
    note "STALE - newest backup is ${newest_name}, ${age_days} day(s) old (threshold ${THRESHOLD_DAYS})"
    exit 1
fi

note "OK - newest backup is ${newest_name}, ${age_days} day(s) old"
exit 0
