#!/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_prod}
DB_USER=${DB_USER:-anxin_prod}
DB_PASSWORD=${DB_PASSWORD}
MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
RETENTION_DAYS=${BACKUP_RETENTION_DAYS:-30}

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

# 创建备份目录
mkdir -p "${BACKUP_DIR}/daily"
mkdir -p "${BACKUP_DIR}/weekly"
mkdir -p "${BACKUP_DIR}/monthly"

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

# 全量备份
BACKUP_FILE="${BACKUP_DIR}/daily/${DB_NAME}_${DATE}.sql.gz"
log "Creating full backup: ${BACKUP_FILE}"

mysqldump -h anxin-mysql \
    -u root \
    -p"${MYSQL_ROOT_PASSWORD}" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --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

# 周备份 (每周日)
if [ $(date +%u) -eq 7 ]; then
    WEEKLY_BACKUP="${BACKUP_DIR}/weekly/${DB_NAME}_week_${DATE}.sql.gz"
    log "Creating weekly backup: ${WEEKLY_BACKUP}"
    cp "${BACKUP_FILE}" "${WEEKLY_BACKUP}"
fi

# 月备份 (每月1号)
if [ $(date +%d) -eq 01 ]; then
    MONTHLY_BACKUP="${BACKUP_DIR}/monthly/${DB_NAME}_month_${DATE}.sql.gz"
    log "Creating monthly backup: ${MONTHLY_BACKUP}"
    cp "${BACKUP_FILE}" "${MONTHLY_BACKUP}"
fi

# 清理过期备份
log "Cleaning up old backups..."

# 清理日备份 (保留指定天数)
find "${BACKUP_DIR}/daily" -name "*.sql.gz" -mtime +${RETENTION_DAYS} -delete
log "Cleaned up daily backups older than ${RETENTION_DAYS} days"

# 清理周备份 (保留12周)
find "${BACKUP_DIR}/weekly" -name "*.sql.gz" -mtime +84 -delete
log "Cleaned up weekly backups older than 12 weeks"

# 清理月备份 (保留12个月)
find "${BACKUP_DIR}/monthly" -name "*.sql.gz" -mtime +365 -delete
log "Cleaned up monthly backups older than 12 months"

# 备份统计
DAILY_COUNT=$(ls -1 "${BACKUP_DIR}/daily"/*.sql.gz 2>/dev/null | wc -l)
WEEKLY_COUNT=$(ls -1 "${BACKUP_DIR}/weekly"/*.sql.gz 2>/dev/null | wc -l)
MONTHLY_COUNT=$(ls -1 "${BACKUP_DIR}/monthly"/*.sql.gz 2>/dev/null | wc -l)

log "Backup statistics: Daily: ${DAILY_COUNT}, Weekly: ${WEEKLY_COUNT}, Monthly: ${MONTHLY_COUNT}"

# 发送备份状态通知 (如果配置了通知)
if [ -n "${BACKUP_NOTIFICATION_URL}" ]; then
    curl -X POST "${BACKUP_NOTIFICATION_URL}" \
        -H "Content-Type: application/json" \
        -d "{\"status\":\"success\",\"message\":\"Production database backup completed\",\"timestamp\":\"${DATE}\"}" \
        2>/dev/null || log "Failed to send backup notification"
fi

log "Production database backup process completed successfully"