#!/bin/bash

# 遇到任何错误即停止执行
set -e

echo "------------------------------------------------"
echo "开始安装 Docker (Debian 专用脚本)"
echo "当前用户: $USER"
echo "------------------------------------------------"

# 1. 更新索引并安装基础依赖
echo "步骤 1: 正在更新软件包列表并安装 ca-certificates 与 curl..."
apt update
apt install -y ca-certificates curl
echo "✅ 基础依赖安装完成。"

# 2. 添加 Docker 官方 GPG 密钥
echo "步骤 2: 正在下载并配置 Docker 官方 GPG 密钥..."
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc
echo "✅ GPG 密钥配置完成。"

# 3. 将软件源添加到 Apt sources
echo "步骤 3: 正在添加 Docker 官方软件源到系统配置..."
tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/debian
Suites: $(. /etc/os-release && echo "$VERSION_CODENAME")
Components: stable
Signed-By: /etc/apt/keyrings/docker.asc
EOF
echo "✅ 软件源添加完成。"

# 4. 再次更新索引并正式安装 Docker
echo "步骤 4: 正在进行最后的系统更新并安装 Docker 核心组件..."
apt update
apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
echo "✅ Docker 引擎安装完成。"

# 5. 验证并启动服务
echo "步骤 5: 正在检查 Docker 服务状态..."
systemctl enable docker
systemctl start docker

echo "------------------------------------------------"
echo "🎉 安装成功！"
echo "Docker 版本信息："
docker --version
echo "Docker Compose 版本信息："
docker compose version
echo "------------------------------------------------"