#!/bin/bash
set -e

handle_error(){
    echo "❌ 脚本执行失败: $1"
    exit 1
}

echo "🚀 开始在 Debian 13 (Trixie) 安装 Docker..."

# 更新 apt
echo "🔄 更新 apt..."
  apt-get update -y || handle_error "更新 apt 失败"

# 安装依赖
echo "📦 安装依赖..."
  apt-get install -y \
    ca-certificates \
    curl \
    gnupg \
    lsb-release || handle_error "安装依赖失败"

# 创建 keyrings 目录
  mkdir -p /etc/apt/keyrings

# 添加 Docker 官方 GPG 密钥（使用阿里云镜像）
echo "🔑 添加 Docker GPG 密钥..."
curl -fsSL http://mirrors.aliyun.com/docker-ce/linux/debian/gpg | \
      gpg --dearmor -o /etc/apt/keyrings/docker.gpg || handle_error "添加 Docker GPG 密钥失败"

# 添加 Docker 阿里云 apt 源
echo "🧩 添加 Docker 阿里云 apt 源..."
DISTRO=$(lsb_release -cs || echo "trixie")
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
http://mirrors.aliyun.com/docker-ce/linux/debian $DISTRO stable" | \
  tee /etc/apt/sources.list.d/docker.list > /dev/null || handle_error "添加 Docker 源失败"

# 更新 apt 缓存
  apt-get update -y || handle_error "更新 apt 缓存失败"

# 安装 Docker
echo "🐳 安装 Docker..."
  apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin || handle_error "安装 Docker 失败"

# 检查版本
docker --version || handle_error "Docker 未安装成功"

# 启动并设置开机自启
echo "⚙️ 启动 Docker 并设置开机启动..."
  systemctl enable docker || handle_error "设置 Docker 开机启动失败"
  systemctl start docker || handle_error "启动 Docker 失败"

# 配置镜像加速
echo "🌐 配置 Docker 镜像加速..."
  mkdir -p /etc/docker
  tee /etc/docker/daemon.json <<-'EOF'
{
    "registry-mirrors": [
        "https://docker.m.daocloud.io",
        "https://docker.imgdb.de",
        "https://docker-0.unsee.tech",
        "https://docker.hlmirror.com",
        "https://docker.1ms.run",
        "https://func.ink",
        "https://lispy.org",
        "https://docker.xiaogenban1993.com"
    ]
}
EOF

# 重启 Docker
  systemctl daemon-reexec
  systemctl daemon-reload
  systemctl restart docker

echo "✅ Docker 安装完成!"
docker info | grep "Server Version" || true
