#!/bin/bash

set -e

echo "Removing old Docker versions..."
for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do 
    sudo apt-get remove -y $pkg || true
done

# Detect OS
if grep -q "Ubuntu" /etc/os-release 2>/dev/null; then
    DOCKER_OS="ubuntu"
    # Source the os-release file to get variables
    . /etc/os-release
    # Use UBUNTU_CODENAME with fallback to VERSION_CODENAME
    CODENAME=${UBUNTU_CODENAME:-$VERSION_CODENAME}
elif [ -f /etc/debian_version ]; then
    DOCKER_OS="debian"
    # Source the os-release file to get VERSION_CODENAME
    . /etc/os-release
    CODENAME=$VERSION_CODENAME
else
    echo "Error: Unsupported OS"
    exit 1
fi
echo "Detected OS: ${DOCKER_OS}, Codename: ${CODENAME}"

echo "Updating package list and installing dependencies..."
sudo apt-get update
sudo apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release

echo "Setting up Docker repository..."
# Add Docker's official GPG key
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/${DOCKER_OS}/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# Add the repository to Apt sources
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/${DOCKER_OS} \
  ${CODENAME} stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

echo "Installing Docker..."
sudo apt-get update
sudo apt-get install -y \
    docker-ce \
    docker-ce-cli \
    containerd.io \
    docker-buildx-plugin \
    docker-compose-plugin

# Verify installation
echo "Verifying Docker installation..."
sudo docker --version
sudo containerd --version

echo "Configuring Docker permissions..."
sudo groupadd docker 2>/dev/null || true
sudo usermod -aG docker ${SUDO_USER:-$USER}

# Check if we're running in a systemd environment
echo "Checking for systemd..."
if pidof systemd > /dev/null && [ -d /run/systemd/system ]; then
    echo "systemd detected - enabling and starting Docker services using systemctl..."
    sudo systemctl enable --now docker.service
    sudo systemctl enable --now containerd.service
else
    echo "systemd not detected (likely in a container) - starting Docker daemon directly..."
    # For containers or non-systemd environments, we can just start the Docker daemon directly
    sudo dockerd > /dev/null 2>&1 &
    echo "Docker daemon started in background."
fi

echo "Docker setup completed. Please log out and log back in for group changes to take effect."
