Files
tg_tinder_bot/bin/backup_db.sh
2025-11-06 15:09:15 +09:00

55 lines
1.8 KiB
Bash

#!/bin/bash
# backup_db.sh - Script for backing up the PostgreSQL database
echo "📦 Backing up PostgreSQL database..."
# Default backup directory
BACKUP_DIR="${BACKUP_DIR:-/var/backups/tg_tinder_bot}"
BACKUP_FILENAME="tg_tinder_bot_$(date +%Y%m%d_%H%M%S).sql"
BACKUP_PATH="$BACKUP_DIR/$BACKUP_FILENAME"
# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"
# Check if running in docker-compose environment
if [ -f /.dockerenv ] || [ -f /proc/self/cgroup ] && grep -q docker /proc/self/cgroup; then
echo "🐳 Running in Docker environment, using docker-compose exec..."
docker-compose exec -T db pg_dump -U postgres telegram_tinder_bot > "$BACKUP_PATH"
else
# Check if PGPASSWORD is set in environment
if [ -z "$PGPASSWORD" ]; then
# If .env file exists, try to get password from there
if [ -f .env ]; then
DB_PASSWORD=$(grep DB_PASSWORD .env | cut -d '=' -f2)
export PGPASSWORD="$DB_PASSWORD"
else
echo "⚠️ No DB_PASSWORD found in environment or .env file."
echo "Please enter PostgreSQL password:"
read -s PGPASSWORD
export PGPASSWORD
fi
fi
echo "💾 Backing up database to $BACKUP_PATH..."
pg_dump -h localhost -U postgres -d telegram_tinder_bot > "$BACKUP_PATH"
fi
# Check if backup was successful
if [ $? -eq 0 ]; then
echo "✅ Backup completed successfully: $BACKUP_PATH"
echo "📊 Backup size: $(du -h $BACKUP_PATH | cut -f1)"
# Compress the backup
gzip -f "$BACKUP_PATH"
echo "🗜️ Compressed backup: $BACKUP_PATH.gz"
# Keep only the last 7 backups
echo "🧹 Cleaning up old backups..."
find "$BACKUP_DIR" -name "tg_tinder_bot_*.sql.gz" -type f -mtime +7 -delete
echo "🎉 Backup process completed!"
else
echo "❌ Backup failed!"
exit 1
fi