docker检测安装最新版和镜像加速

accelerator_address="https://docker.mirrors.ustc.edu.cn/"
oldpackages=("docker.io" "docker-doc" "docker-compose-v2" "podman-docker" "runc")
newpackages=("docker-ce" "docker-ce-cli" "containerd.io" "docker-buildx-plugin" "docker-compose-plugin")

# docker安装标志
docker_installed=false

# 检测旧包是否存在,存在配置安装标志,跳出检测
for pkg in "${OLDPACKAGES[@]}"; do
  if dpkg -l | grep -q $pkg; then
    yellow_echo "检测到docker旧包 $pkg,已经安装,将重新安装"
    DOCKER_INSTALLED=true
    break
  fi
done

# 检测新包是否不存在,不存在配置安装标志,跳出检测
for pkg in "${NEWPACKAGES[@]}"; do
  if ! dpkg -l | grep -q $pkg; then
    yellow_echo "检测到新包 $pkg,未安装,将重新安装"
    DOCKER_INSTALLED=true
    break
  fi
done

# docker安装标志为true,重新安装docker
if $DOCKER_INSTALLED; then
    green_echo '安装 Docker...'

    # 删除旧的 Docker 安装
    sudo apt autoremove -y docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc

    # Add Docker's official GPG key:
    sudo apt-get update
    sudo apt-get install ca-certificates curl gnupg
    sudo install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    sudo chmod a+r /etc/apt/keyrings/docker.gpg

    # 添加清华大学的Docker存储库
    echo \
      "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/ubuntu \
      "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
      sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

    # 使用中科大的镜像加速器
    green_echo "设置中科大镜像源加速: $ACCELERATOR_ADDRESS"
    sudo mkdir -p /etc/docker
    echo '{ "registry-mirrors": ["'$ACCELERATOR_ADDRESS'"] }' | sudo tee /etc/docker/daemon.json > /dev/null

    # 官方安装docker的方法
    sudo apt-get update
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

    # 启动并使 Docker 开机自启
    sudo systemctl enable docker
    sudo systemctl start docker

    echo 'Docker 安装完成。'
fi