#!/bin/bash
# backup-audit-check.sh — Daily check: was yesterday's full backup successful?
# Runs ~1h after scheduled backup (2 AM UTC, backup at 1 AM UTC).
# Exits 0 = OK, exits 1 = stale/missing.
# Logs to syslog tag 'backup-audit'.
# System crontab entry: 0 2 * * * /root/.hermes/scripts/backup-audit-check.sh 2>&1 | logger -t backup-audit

set -euo pipefail

ENDPOINT="https://s3.us-east-1.wasabisys.com"
BUCKET="hermes-vps-backups"
PREFIX="hermes-full-backup"

if [ -f /opt/awscli-venv/bin/activate ]; then
    source /opt/awscli-venv/bin/activate
fi

latest=$(aws s3 ls "s3://$BUCKET/$PREFIX/" --endpoint-url "$ENDPOINT" 2>&1 | grep "\.tar\.gz$" | sort | tail -1)

if [ -z "$latest" ]; then
    echo "[BACKUP-AUDIT] No full backup archives found on S3!"
    exit 1
fi

date_str=$(echo "$latest" | awk '{print $1}')
size_bytes=$(echo "$latest" | awk '{print $3}')
file_name=$(echo "$latest" | awk '{print $4}')

backup_epoch=$(date -d "$date_str" +%s 2>/dev/null || date -j -f "%Y-%m-%d" "$date_str" +%s 2>/dev/null)
now_epoch=$(date +%s)
age_hours=$(( (now_epoch - backup_epoch) / 3600 ))

if [ "$age_hours" -lt 36 ]; then
    echo "[BACKUP-AUDIT] OK — Last: $file_name ($date_str, ${size_bytes}B, ${age_hours}h ago)"
    exit 0
elif [ "$age_hours" -lt 60 ]; then
    echo "[BACKUP-AUDIT] WARNING — Last backup $age_hours hours old: $file_name"
    exit 0
else
    echo "[BACKUP-AUDIT] STALE — Last backup was $age_hours hours ago: $file_name"
    exit 1
fi
