#!/bin/bash

# 确保脚本以 root 权限运行
if [ "$EUID" -ne 0 ]; then 
  echo "请使用 sudo 运行此脚本"
  exit
fi

echo "--- 开始安装 Docker ---"

# 1. 更新索引并安装基础依赖
echo "步骤 1: 更新包索引并安装证书工具..."
apt-get update
apt-get install -y ca-certificates curl

# 2. 添加 Docker 官方 GPG 密钥
echo "步骤 2: 配置 Docker GPG 密钥..."
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc

# 3. 添加 Docker 存储库到 Apt 源
echo "步骤 3: 添加 Docker 存储库..."
cat <<EOF > /etc/apt/sources.list.d/docker.list
deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable
EOF

# 4. 安装 Docker 组件
echo "步骤 4: 安装 Docker 引擎及插件..."
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 5. 启动并验证
echo "步骤 5: 启动 Docker 并设置开机自启..."
systemctl enable docker
systemctl start docker

echo "--- 安装完成！ ---"
docker --version
systemctl status docker --no-pager
