#!/usr/bin/env bash
#
# Afimon — Docker Engine install for Ubuntu 24.04 (noble) и новее.
#

set -euo pipefail

if [[ "${EUID}" -ne 0 ]]; then
    echo "Run this script as root: sudo $0"
    exit 1
fi

if [[ ! -r /etc/os-release ]]; then
    echo "Cannot detect operating system."
    exit 1
fi

source /etc/os-release

if [[ "${ID:-}" != "ubuntu" ]]; then
    echo "This script supports Ubuntu only. Detected: ${PRETTY_NAME:-unknown}"
    exit 1
fi

UBUNTU_MAJOR="${VERSION_ID%%.*}"
if [[ -z "${UBUNTU_MAJOR}" ]] || ! awk -v v="${UBUNTU_MAJOR}" 'BEGIN{exit !(v+0 >= 24)}'; then
    echo "This script supports Ubuntu 24.04+. Detected: ${PRETTY_NAME:-unknown} (VERSION_ID=${VERSION_ID:-?})"
    exit 1
fi

export DEBIAN_FRONTEND=noninteractive

echo "Removing conflicting packages..."
conflicting_packages=(
    docker.io
    docker-compose
    docker-compose-v2
    docker-doc
    podman-docker
    containerd
    runc
)
for package in "${conflicting_packages[@]}"; do
    apt-get remove -y "$package" 2>/dev/null || true
done

echo "Installing prerequisites..."
apt-get update
apt-get install -y ca-certificates curl

echo "Adding Docker repository key..."
install -m 0755 -d /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg \
    -o /etc/apt/keyrings/docker.asc
chmod a+r /etc/apt/keyrings/docker.asc

echo "Adding Docker repository..."
cat > /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: ${VERSION_CODENAME:-noble}
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF

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

echo "Enabling Docker..."
systemctl enable --now docker

echo
echo "Docker installed successfully."
docker --version
docker compose version