#!/bin/bash
# =============================================================================
# MinIO Object Storage - 部署脚本
# =============================================================================
#
# 用法:
#   ./deploy.sh up              启动 MinIO
#   ./deploy.sh down            停止 MinIO
#   ./deploy.sh restart         重启 MinIO
#   ./deploy.sh logs            查看日志
#   ./deploy.sh status          查看状态
#   ./deploy.sh health          健康检查
#   ./deploy.sh create-bucket <name>  创建存储桶
#   ./deploy.sh list-buckets    列出所有存储桶
#   ./deploy.sh info            查看服务器信息
#   ./deploy.sh backup          备份配置
#
# 示例:
#   ./deploy.sh up                     # 启动 MinIO
#   ./deploy.sh create-bucket uploads  # 创建 uploads 存储桶
#   ./deploy.sh logs -f                # 实时查看日志
#
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 配置
COMPOSE_FILE="docker-compose.yml"
ENV_FILE=".env"
ENV_EXAMPLE=".env.example"

# =============================================================================
# 工具函数
# =============================================================================

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${CYAN}[STEP]${NC} $1"
}

# 检查 .env 文件
check_env() {
    if [ ! -f "$ENV_FILE" ]; then
        if [ -f "$ENV_EXAMPLE" ]; then
            log_info "创建 .env 文件..."
            cp "$ENV_EXAMPLE" "$ENV_FILE"
            log_warning "请检查 .env 文件并配置必要的环境变量"
            log_warning "特别注意: MINIO_ROOT_PASSWORD 必须修改为安全密码"
        else
            log_error ".env.example 文件不存在"
            exit 1
        fi
    fi

    # 加载环境变量
    if [ -f "$ENV_FILE" ]; then
        export $(grep -v '^#' "$ENV_FILE" | xargs)
    fi
}

# 检查数据目录
check_data_dir() {
    local data_path="${MINIO_DATA_PATH:-/data/minio}"
    if [ ! -d "$data_path" ]; then
        log_info "创建数据目录: $data_path"
        sudo mkdir -p "$data_path"
        sudo chown -R 1000:1000 "$data_path"
        log_success "数据目录已创建"
    fi
}

# 获取 MinIO 连接信息
get_minio_endpoint() {
    echo "http://localhost:${MINIO_API_PORT:-9000}"
}

# 配置 mc 客户端
setup_mc() {
    local endpoint=$(get_minio_endpoint)
    local user="${MINIO_ROOT_USER:-admin}"
    local password="${MINIO_ROOT_PASSWORD:-minio_secret_password}"

    if command -v mc &> /dev/null; then
        mc alias set rwa "$endpoint" "$user" "$password" --api S3v4 > /dev/null 2>&1
        return 0
    else
        # 使用 docker 中的 mc
        docker exec rwa-minio mc alias set local http://localhost:9000 "$user" "$password" --api S3v4 > /dev/null 2>&1
        return 0
    fi
}

# =============================================================================
# 命令实现
# =============================================================================

cmd_up() {
    check_env
    check_data_dir

    log_info "启动 MinIO 对象存储..."
    docker compose -f "$COMPOSE_FILE" up -d

    log_info "等待服务启动..."
    sleep 5

    log_success "MinIO 已启动！"
    echo ""
    cmd_status
}

cmd_down() {
    log_info "停止 MinIO..."
    docker compose -f "$COMPOSE_FILE" down
    log_success "MinIO 已停止"
}

cmd_restart() {
    log_info "重启 MinIO..."
    docker compose -f "$COMPOSE_FILE" restart minio
    log_success "MinIO 已重启"
}

cmd_logs() {
    docker compose -f "$COMPOSE_FILE" logs "$@" minio
}

cmd_status() {
    echo ""
    echo "=========================================="
    echo "  MinIO Object Storage 状态"
    echo "=========================================="
    echo ""

    docker compose -f "$COMPOSE_FILE" ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"

    echo ""
    echo "=========================================="
    echo "  访问地址"
    echo "=========================================="
    echo ""
    echo "  S3 API:     http://localhost:${MINIO_API_PORT:-9000}"
    echo "  Console:    http://localhost:${MINIO_CONSOLE_PORT:-9001}"
    echo ""
    echo "  默认凭证:"
    echo "    用户名: ${MINIO_ROOT_USER:-admin}"
    echo "    密码:   (见 .env 文件)"
    echo ""
}

cmd_health() {
    echo ""
    echo "=========================================="
    echo "  MinIO 健康检查"
    echo "=========================================="
    echo ""

    local endpoint=$(get_minio_endpoint)

    # 检查 API 端点
    if curl -s "${endpoint}/minio/health/live" > /dev/null 2>&1; then
        echo -e "  API Health:     ${GREEN}✓ Live${NC}"
    else
        echo -e "  API Health:     ${RED}✗ Not responding${NC}"
    fi

    # 检查就绪状态
    if curl -s "${endpoint}/minio/health/ready" > /dev/null 2>&1; then
        echo -e "  Ready Status:   ${GREEN}✓ Ready${NC}"
    else
        echo -e "  Ready Status:   ${RED}✗ Not ready${NC}"
    fi

    # 检查集群状态
    if curl -s "${endpoint}/minio/health/cluster" > /dev/null 2>&1; then
        echo -e "  Cluster:        ${GREEN}✓ Healthy${NC}"
    else
        echo -e "  Cluster:        ${YELLOW}○ Standalone mode${NC}"
    fi

    echo ""
}

cmd_create_bucket() {
    local bucket_name="$1"
    if [ -z "$bucket_name" ]; then
        log_error "请提供存储桶名称"
        echo "用法: $0 create-bucket <bucket-name>"
        exit 1
    fi

    check_env
    setup_mc

    log_info "创建存储桶: $bucket_name"

    if command -v mc &> /dev/null; then
        mc mb --ignore-existing "rwa/$bucket_name"
    else
        docker exec rwa-minio mc mb --ignore-existing "local/$bucket_name"
    fi

    log_success "存储桶 '$bucket_name' 已创建"
}

cmd_list_buckets() {
    check_env
    setup_mc

    echo ""
    echo "=========================================="
    echo "  MinIO 存储桶列表"
    echo "=========================================="
    echo ""

    if command -v mc &> /dev/null; then
        mc ls rwa
    else
        docker exec rwa-minio mc ls local
    fi

    echo ""
}

cmd_info() {
    check_env
    setup_mc

    echo ""
    echo "=========================================="
    echo "  MinIO 服务器信息"
    echo "=========================================="
    echo ""

    if command -v mc &> /dev/null; then
        mc admin info rwa
    else
        docker exec rwa-minio mc admin info local
    fi

    echo ""
}

cmd_backup() {
    check_env
    local backup_dir="${SCRIPT_DIR}/backups"
    local timestamp=$(date +"%Y%m%d_%H%M%S")
    local backup_file="${backup_dir}/minio_config_${timestamp}.tar.gz"

    mkdir -p "$backup_dir"

    log_info "备份 MinIO 配置..."

    # 备份 .env 和 docker-compose 配置
    tar -czf "$backup_file" \
        -C "$SCRIPT_DIR" \
        .env docker-compose.yml 2>/dev/null || true

    log_success "配置已备份到: $backup_file"
}

cmd_help() {
    echo ""
    echo "MinIO Object Storage 部署工具"
    echo ""
    echo "用法: $0 <命令> [参数...]"
    echo ""
    echo "命令:"
    echo "  up              启动 MinIO"
    echo "  down            停止 MinIO"
    echo "  restart         重启 MinIO"
    echo "  logs [options]  查看日志 (支持 -f 参数)"
    echo "  status          查看运行状态"
    echo "  health          健康检查"
    echo "  create-bucket   创建存储桶"
    echo "  list-buckets    列出所有存储桶"
    echo "  info            查看服务器信息"
    echo "  backup          备份配置"
    echo "  help            显示帮助"
    echo ""
    echo "示例:"
    echo "  $0 up                       # 启动 MinIO"
    echo "  $0 logs -f                  # 实时查看日志"
    echo "  $0 create-bucket uploads    # 创建 uploads 存储桶"
    echo "  $0 list-buckets             # 列出所有存储桶"
    echo ""
    echo "环境变量 (可在 .env 中配置):"
    echo "  MINIO_ROOT_USER        管理员用户名 (默认: admin)"
    echo "  MINIO_ROOT_PASSWORD    管理员密码"
    echo "  MINIO_API_PORT         S3 API 端口 (默认: 9000)"
    echo "  MINIO_CONSOLE_PORT     Web 控制台端口 (默认: 9001)"
    echo "  MINIO_DATA_PATH        数据存储路径 (默认: /data/minio)"
    echo ""
}

# =============================================================================
# 主入口
# =============================================================================

case "${1:-help}" in
    up)
        cmd_up
        ;;
    down)
        cmd_down
        ;;
    restart)
        cmd_restart
        ;;
    logs)
        shift
        cmd_logs "$@"
        ;;
    status)
        cmd_status
        ;;
    health)
        cmd_health
        ;;
    create-bucket)
        shift
        cmd_create_bucket "$@"
        ;;
    list-buckets)
        cmd_list_buckets
        ;;
    info)
        cmd_info
        ;;
    backup)
        cmd_backup
        ;;
    help|--help|-h)
        cmd_help
        ;;
    *)
        log_error "未知命令: $1"
        cmd_help
        exit 1
        ;;
esac
