#!/bin/bash set -e # Backup Health Check Script # Ensures backup integrity and database health DB_NAME="datashield" DB_USER="collabhubmaster" DB_HOST="postgres" DB_PORT="5432" BACKUP_DIR="/backups" echo "🔍 Running backup and database health check..." # Check if database is accessible echo "📡 Testing database connection..." if pg_isready -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME"; then echo "✅ Database is accessible" else echo "❌ Database is not accessible!" exit 1 fi # Check database size and basic statistics echo "📊 Database statistics:" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c " SELECT 'Database Size' as metric, pg_size_pretty(pg_database_size('$DB_NAME')) as value UNION ALL SELECT 'Total Users' as metric, COUNT(id)::text as value FROM datashield.users UNION ALL SELECT 'Total Files' as metric, COUNT(id)::text as value FROM datashield.files UNION ALL SELECT 'Active Files' as metric, COUNT(id)::text as value FROM datashield.files WHERE trashed = FALSE; " 2>/dev/null || echo "⚠️ Could not fetch database statistics" # Check latest backup echo "💾 Checking latest backup..." LATEST_BACKUP=$(ls -t "$BACKUP_DIR"/datashield_backup_*.sql 2>/dev/null | head -n1) if [ -n "$LATEST_BACKUP" ]; then echo "✅ Latest backup found: $(basename "$LATEST_BACKUP")" # Verify backup integrity if [ -f "${LATEST_BACKUP}.sha256" ]; then echo "🔐 Verifying backup integrity..." if sha256sum -c "${LATEST_BACKUP}.sha256" >/dev/null 2>&1; then echo "✅ Backup integrity verified" else echo "❌ Backup integrity check failed!" exit 1 fi else echo "⚠️ No checksum file found for latest backup" fi echo "📊 Backup size: $(du -h "$LATEST_BACKUP" | cut -f1)" echo "📅 Backup created: $(stat -c %y "$LATEST_BACKUP" 2>/dev/null || stat -f %Sm "$LATEST_BACKUP" 2>/dev/null)" else echo "⚠️ No backups found" fi # Check materialized view freshness echo "🔄 Checking materialized view freshness..." psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c " SELECT 'Analytics View Last Refresh' as metric, MAX(u.last_active) as value FROM datashield.user_analytics ua JOIN datashield.users u ON ua.domain = u.domain; " 2>/dev/null || echo "⚠️ Could not check materialized view" # Check database connections echo "🔗 Connection statistics:" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c " SELECT 'Active Connections' as metric, count(*)::text as value FROM pg_stat_activity WHERE state = 'active'; " 2>/dev/null || echo "⚠️ Could not fetch connection statistics" echo "✅ Health check completed!"