#!/usr/bin/env bash
# backup_freshness.sh — check that backups exist and are recent.
set -euo pipefail

BACKUP_DIRS="${OIKOS_BACKUP_DIRS:-/var/backups /opt/backups /mnt/backups}"
GRACE_HOURS="${OIKOS_BACKUP_GRACE:-48}"
STALE=""

for dir in $BACKUP_DIRS; do
  [ -d "$dir" ] || continue
  NEWEST=$(find "$dir" -type f -mmin -$((GRACE_HOURS * 60)) 2>/dev/null | head -1 || true)
  if [ -z "$NEWEST" ]; then
    LATEST_TS=$(find "$dir" -type f -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -1 | awk '{print $1}' || echo "0")
    LATEST_HOURS=$(awk "BEGIN {printf \"%.0f\", ($(date +%s) - ${LATEST_TS:-0})/3600}")
    STALE="$STALE $dir(${LATEST_HOURS}h)"
  fi
done

if [ -n "$STALE" ]; then
  echo "{\"health\":\"degraded\",\"signalKind\":\"backup-stale\",\"evidence\":\"stale backups:$(echo "$STALE" | sed 's/ /, /g')\"}"
else
  echo '{"health":"healthy"}'
fi
