#!/bin/bash

# Exit on any error
set -e

# Detect distribution
DISTRO=$(lsb_release -i | grep -oE "Ubuntu|Debian")
if [ "$DISTRO" = "Debian" ]; then
  DOCKER_MIRROR="https://mirrors.aliyun.com/docker-ce/linux/debian"
elif [ "$DISTRO" = "Ubuntu" ]; then
  DOCKER_MIRROR="https://mirrors.aliyun.com/docker-ce/linux/ubuntu"
else
  echo "Error: Unsupported distribution $DISTRO. Only Debian and Ubuntu are supported."
  exit 1
fi

# Update package index and install dependencies
apt-get update
apt-get install -y -y ca-certificates curl gnupg

# Create keyrings directory if it doesn't exist
install -m 0755 -d /etc/apt/keyrings

# Download and configure Aliyun GPG key
curl -fsSL ${DOCKER_MIRROR}/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

# Add Aliyun Docker repository in DEB822 format
cat <<EOF >/etc/apt/sources.list.d/docker.sources
Types: deb
URIs: ${DOCKER_MIRROR}
Suites: $(lsb_release -cs)
Components: stable
Signed-By: /etc/apt/keyrings/docker.gpg
Architectures: amd64
Enabled: yes
EOF

# Update package index and install Docker
apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# Verify Docker installation
docker --version

# Optional: Add current user to docker group to run Docker without sudo
usermod -aG docker $USER

echo "Docker installed successfully. Log out and log back in to use Docker without sudo."
