#!/bin/bash
# 测试环境数据库备份脚本
# Requirements: 5.3, 6.5

set -e

# 配置变量
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d_%H%M%S)
DB_NAME=${DB_NAME:-anxin_staging}
DB_USER=${DB_USER:-anxin_staging}
DB_PASSWORD=${DB_PASSWORD:-staging_password}
MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-staging_root_password}
RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-7}

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

# 创建备份目录
mkdir -p "${BACKUP_DIR}"

# 执行数据库备份
log "Starting database backup for staging environment..."

BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${DATE}.sql.gz"
log "Creating backup: ${BACKUP_FILE}"

mysqldump -h anxin-mysql \
    -u root \
    -p"${MYSQL_ROOT_PASSWORD}" \
    --single-transaction \
    --routines \
    --triggers \
    --hex-blob \
    --opt \
    --lock-tables=false \
    "${DB_NAME}" | gzip > "${BACKUP_FILE}"

if [ $? -eq 0 ]; then
    log "Database backup completed successfully"
    
    # 验证备份文件
    if [ -f "${BACKUP_FILE}" ] && [ -s "${BACKUP_FILE}" ]; then
        log "Backup file verification passed: $(du -h ${BACKUP_FILE} | cut -f1)"
    else
        log "ERROR: Backup file verification failed"
        exit 1
    fi
else
    log "ERROR: Database backup failed"
    exit 1
fi

# 清理过期备份
log "Cleaning up old backups..."
find "${BACKUP_DIR}" -name "*.sql.gz" -mtime +${RETENTION_DAYS} -delete
log "Cleaned up backups older than ${RETENTION_DAYS} days"

# 备份统计
BACKUP_COUNT=$(ls -1 "${BACKUP_DIR}"/*.sql.gz 2>/dev/null | wc -l)
log "Current backup count: ${BACKUP_COUNT}"

log "Staging database backup process completed successfully"