#!/bin/bash
set -e

# 定义变量
DOCKER_TAR="docker-25.0.0.tgz"
SYSTEMD_DIR="/lib/systemd/system"
BIN_DIR="/usr/local/bin"

# 0. 停止旧版本服务（如有）
sudo systemctl stop docker containerd.socket containerd 2>/dev/null || true

# 1. 解压Docker二进制包
echo "解压Docker二进制包..."
sudo tar -xzvf ${DOCKER_TAR} -C ${BIN_DIR} --strip-components=1

# 2. 确保二进制文件可执行
sudo chmod +x ${BIN_DIR}/{containerd,ctr,dockerd,docker,runc}

# 3. 配置containerd.service
echo "配置containerd服务..."
cat > ${SYSTEMD_DIR}/containerd.service  <<'EOF'
[Unit]
Description=containerd container runtime
Documentation=https://containerd.io
After=network.target local-fs.target

[Service]
ExecStartPre=-/sbin/modprobe overlay
ExecStart=${BIN_DIR}/containerd
KillMode=process
Delegate=yes
LimitNOFILE=1048576
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity

[Install]
WantedBy=multi-user.target
EOF

# 4. 配置docker.service
echo "配置Docker服务..."
cat > ${SYSTEMD_DIR}/docker.service <<'EOF'
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target docker.socket containerd.service
Wants=network-online.target
Requires=docker.socket containerd.service

[Service]
Type=notify
ExecStart=${BIN_DIR}/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yes
KillMode=process
OOMScoreAdjust=-500

[Install]
WantedBy=multi-user.target
EOF

# 5. 配置docker.socket
echo "配置Docker Socket..."
cat >  ${SYSTEMD_DIR}/docker.socket <<'EOF'
[Unit]
Description=Docker Socket for the API
PartOf=docker.service

[Socket]
ListenStream=/var/run/docker.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target
EOF

# 6. 创建docker用户组
echo "配置用户组..."
sudo groupadd -f docker
sudo usermod -aG docker $USER 2>/dev/null && echo "已添加用户 $USER 到docker组"

# 7. 启用并启动服务
echo "启动服务..."
sudo systemctl daemon-reload
sudo systemctl enable --now containerd docker

# 8. 验证安装
echo -e "\n验证状态："
sudo systemctl status containerd docker | grep "Active:"
echo -e "\nDocker版本："
${BIN_DIR}/docker --version
