#!/usr/bin/env bash
# Backup integrity and compliance checker — validates 3-2-1-1-0 backup rule.
# Usage: bash scripts/backup_check.sh [--backup-dir /path/to/backups]
set -euo pipefail

BACKUP_DIR="${1:-/var/backups}"

echo "=== Backup Security Check ==="
echo "Checking: $BACKUP_DIR"
echo ""

SCORE=0
MAX=5

echo "--- 3-2-1-1-0 Backup Rule ---"

# Check 3: At least 3 copies
echo -n "  3 copies:    "
if [ -d "$BACKUP_DIR" ]; then
  COUNT=$(find "$BACKUP_DIR" -name "*.tar.gz" -o -name "*.bak" -o -name "*.sql" -o -name "*.dump" -o -name "*.zip" 2>/dev/null | wc -l)
  if [ "$COUNT" -ge 3 ]; then
    echo "✅ $COUNT backup files found"; ((SCORE++))
  else
    echo "⚠️  Only $COUNT files (need 3+)"
  fi
else
  echo "🔴 Backup directory not found"
fi

# Check 2: Two different media types (check for local + remote indicators)
echo -n "  2 media:     "
HAS_LOCAL=$([ -d "$BACKUP_DIR" ] && echo "yes" || echo "no")
HAS_REMOTE=$(mount | grep -qiE "nfs|cifs|s3|fuse" && echo "yes" || echo "no")
if [ "$HAS_LOCAL" = "yes" ] && [ "$HAS_REMOTE" = "yes" ]; then
  echo "✅ Local + remote storage detected"; ((SCORE++))
else
  echo "⚠️  Verify backups exist on different media types"
fi

# Check 1: One offsite
echo -n "  1 offsite:   "
echo "ℹ️  Verify manually — check cloud/offsite backup configuration"

# Check 1: One immutable
echo -n "  1 immutable: "
IMMUTABLE=$(lsattr "$BACKUP_DIR"/*.* 2>/dev/null | grep -c "i" || echo 0)
if [ "$IMMUTABLE" -gt 0 ]; then
  echo "✅ $IMMUTABLE immutable files found"; ((SCORE++))
else
  echo "⚠️  No immutable backups detected (use chattr +i or object lock)"
fi

# Check 0: Zero errors
echo -n "  0 errors:    "
RECENT=$(find "$BACKUP_DIR" -name "*.tar.gz" -mtime -7 2>/dev/null | head -1)
if [ -n "$RECENT" ]; then
  if tar tzf "$RECENT" &>/dev/null; then
    echo "✅ Most recent backup integrity verified"; ((SCORE++))
  else
    echo "🔴 Most recent backup CORRUPTED!"
  fi
else
  echo "⚠️  No backups from last 7 days"
fi

echo ""
echo "--- Backup Age ---"
if [ -d "$BACKUP_DIR" ]; then
  NEWEST=$(find "$BACKUP_DIR" -type f -name "*.tar.gz" -o -name "*.bak" -o -name "*.sql" 2>/dev/null | xargs ls -t 2>/dev/null | head -1)
  if [ -n "$NEWEST" ]; then
    AGE=$(( ($(date +%s) - $(stat -c %Y "$NEWEST" 2>/dev/null || stat -f %m "$NEWEST" 2>/dev/null || echo 0)) / 86400 ))
    if [ "$AGE" -gt 7 ]; then
      echo "  ⚠️  Newest backup is $AGE days old"
    else
      echo "  ✅ Newest backup is $AGE days old"; ((SCORE++))
    fi
  fi
fi

echo ""
echo "=== Score: $SCORE/$MAX ==="
