#!/bin/bash

# 配置参数
CLUSTER_NAME="informat-file"                # Ceph集群名
BUCKET_NAME="informat-next"                 # 要备份的Bucket
BACKUP_ROOT="/informat/backup/ceph_data"   # 备份根目录
LOG_FILE="/var/log/ceph_backup.log"        # 日志文件
AWS_CLI_PROFILE="ceph-nano"                # AWS CLI配置名称
DATE=$(date +%Y%m%d)                       # 当前日期格式：20240101
AWS_CLI_URL="https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip"
AWS_CLI_INSTALL_DIR="/opt/aws-cli"         # 二进制安装目录

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

# 通过二进制安装awscli
install_awscli_binary() {
    if [[ ! -f "$AWS_CLI_INSTALL_DIR/v2/current/bin/aws" ]]; then
        log "开始安装AWS CLI..."
        
        TMP_DIR=$(mktemp -d)
        curl -s "$AWS_CLI_URL" -o "$TMP_DIR/awscliv2.zip" || {
            log "错误：下载AWS CLI失败！"
            exit 1
        }
        unzip -q "$TMP_DIR/awscliv2.zip" -d "$TMP_DIR" || {
            log "错误：解压AWS CLI失败！"
            exit 1
        }
        
        sudo "$TMP_DIR/aws/install" \
            --bin-dir /usr/local/bin \
            --install-dir "$AWS_CLI_INSTALL_DIR" || {
            log "错误：安装AWS CLI失败！"
            exit 1
        }
        
        rm -rf "$TMP_DIR"
        log "AWS CLI安装成功：$(/usr/local/bin/aws --version 2>&1)"
    fi
}

# 配置Ceph访问
setup_ceph_config() {
    log "获取Ceph集群配置..."
    CLUSTER_INFO=$(cn cluster status "$CLUSTER_NAME" 2>&1)

    ENDPOINT=$(echo "$CLUSTER_INFO" | grep "Endpoint:" | awk '{print $2}')
    ACCESS_KEY=$(echo "$CLUSTER_INFO" | grep "Access key:" | awk '{print $3}')
    SECRET_KEY=$(echo "$CLUSTER_INFO" | grep "Secret key:" | awk '{print $3}')

    [[ -z "$ENDPOINT" || -z "$ACCESS_KEY" || -z "$SECRET_KEY" ]] && {
        log "错误：无法获取Ceph集群配置！"
        exit 1
    }

    mkdir -p ~/.aws
    cat > ~/.aws/config <<EOF
[$AWS_CLI_PROFILE]
region = us-east-1
s3 =
    endpoint_url = $ENDPOINT
    signature_version = s3v4
EOF

    cat > ~/.aws/credentials <<EOF
[$AWS_CLI_PROFILE]
aws_access_key_id = $ACCESS_KEY
aws_secret_access_key = $SECRET_KEY
EOF
    chmod 600 ~/.aws/credentials
}

# 安全备份（仅在成功时清理旧备份）
backup_bucket() {
    local BACKUP_DIR="$BACKUP_ROOT/$DATE"
    local TEMP_DIR="$BACKUP_ROOT/temp_$DATE"
    
    # 先备份到临时目录
    mkdir -p "$TEMP_DIR"
    log "开始备份到临时目录: $TEMP_DIR"
    
    aws s3 sync "s3://$BUCKET_NAME/" "$TEMP_DIR/" \
        --endpoint-url "$ENDPOINT" \
        --profile "$AWS_CLI_PROFILE" \
        --size-only \
        --no-follow-symlinks \
        2>&1 | tee -a "$LOG_FILE"

    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        log "错误：备份失败！保留历史备份。"
        rm -rf "$TEMP_DIR"
        exit 1
    fi

    # 备份成功后才执行清理
    log "备份验证成功，正在清理旧数据..."
    find "$BACKUP_ROOT" -mindepth 1 -maxdepth 1 -type d ! -name "temp_*" -exec rm -rf {} \;
    
    # 重命名临时目录为正式目录
    mv "$TEMP_DIR" "$BACKUP_DIR"
    log "备份最终保存到: $BACKUP_DIR"
}

main() {
    install_awscli_binary
    setup_ceph_config
    backup_bucket
    log "===== 备份完成（已自动清理旧备份） ====="
}

main