set -ex

installDocker() {
  local systemId=$(grep -oP '^ID=\K.*' /etc/os-release)
  
  ## docker
  if systemctl is-active --quiet docker; then
      echo "Docker 服务已存在"
  else
     for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do sudo apt-get remove -y $pkg; done
     
     apt-get update
     apt-get install -y ca-certificates curl gnupg
     
     install -m 0755 -d /etc/apt/keyrings
     rm -f /etc/apt/keyrings/docker.gpg
     curl -fsSL http://mirrors.huaweicloud.com/docker-ce/linux/${systemId}/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
     sudo chmod a+r /etc/apt/keyrings/docker.gpg
     echo \
       "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] http://mirrors.huaweicloud.com/docker-ce/linux/${systemId} \
     "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" |
       tee /etc/apt/sources.list.d/docker.list >/dev/null
     
     apt-get update
     apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  fi

}

updateDocker() {
  mkdir -p /etc/docker /data/.cache/docker
  cat >/etc/docker/daemon.json <<EOF
{
    "data-root": "/data/.cache/docker",
    "features": {
      "containerd-snapshotter": true  
    }
}
EOF

  mkdir -p /root/.docker
  cat >/root/.docker/config.json <<EOF
{
  "auths": {
    "harbor.inner.xcastle.net": {
      "auth": "c2NyZWVuOlR4cnkyMDI1"
    }
  }
}
EOF

 cat >/etc/containerd/config.toml <<EOF
disabled_plugins = ["cri"]
root = "/data/.cache/containerd"
EOF

  systemctl restart containerd
  systemctl restart docker
}


installDocker
updateDocker
