#!/usr/bin/env bash
# Read-only freshness and integrity checks for a directory of backup files.
set -u

backup_dir="${1:-}"
max_age_hours="${2:-24}"

if [[ -z "$backup_dir" || ! -d "$backup_dir" ]]; then
  printf 'Usage: %s BACKUP_DIRECTORY [MAX_AGE_HOURS]\n' "$0" >&2
  exit 2
fi

if [[ ! "$max_age_hours" =~ ^[0-9]+$ ]] || (( max_age_hours < 1 )); then
  printf 'Error: MAX_AGE_HOURS must be a positive integer\n' >&2
  exit 2
fi

newest="$(find "$backup_dir" -maxdepth 1 -type f -printf '%T@\t%p\n' 2>/dev/null |
  sort -n -r | head -n 1 | cut -f2-)"

if [[ -z "$newest" ]]; then
  printf 'CRITICAL: no backup files found in %s\n' "$backup_dir" >&2
  exit 2
fi

now="$(date +%s)"
modified="$(stat -c %Y "$newest")"
age_hours="$(( (now - modified) / 3600 ))"
size="$(du -h "$newest" | cut -f1)"
available="$(df -hP "$backup_dir" | awk 'NR == 2 {print $4}')"

printf 'Backup directory: %s\n' "$backup_dir"
printf 'Newest file: %s\n' "$newest"
printf 'Size: %s\nAge: %s hour(s)\nAvailable space: %s\n' \
  "$size" "$age_hours" "$available"

if ! sha256sum "$newest" >/dev/null; then
  printf 'CRITICAL: newest backup could not be read completely\n' >&2
  exit 2
fi

if (( age_hours > max_age_hours )); then
  printf 'WARNING: newest backup exceeds the %s-hour limit\n' "$max_age_hours" >&2
  exit 1
fi

printf 'Result: healthy\n'
