#!/usr/bin/env bash

set -e

if [[ $EUID -ne 0 ]]; then
    echo "Запустите скрипт от root: sudo bash install_docker.sh"
    exit 1
fi

REAL_USER=${SUDO_USER:-$(whoami)}
echo "Основной пользователь: $REAL_USER"

if [[ -f /etc/os-release ]]; then
    . /etc/os-release
    OS=$ID
    VERSION_ID=$VERSION_ID
else
    echo "Не удалось определить систему!"
    exit 1
fi

echo "Обнаружена система: $OS $VERSION_ID"
sleep 1

echo "Удаление старых версий Docker..."
if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
    apt remove -y docker docker-engine docker.io containerd runc docker-ce docker-ce-cli docker-compose-plugin docker-buildx-plugin || true
    apt autoremove -y || true
    rm -rf /var/lib/docker
    rm -rf /var/lib/containerd
elif [[ "$OS" == "centos" || "$OS" == "rocky" || "$OS" == "almalinux" ]]; then
    yum remove -y docker docker-client docker-client-latest docker-common docker-latest docker-latest-logrotate docker-logrotate docker-engine containerd.io docker-ce docker-ce-cli || true
    rm -rf /var/lib/docker
    rm -rf /var/lib/containerd
fi
echo "Старые версии удалены."
sleep 1

echo "Установка Docker..."
if [[ "$OS" == "ubuntu" || "$OS" == "debian" ]]; then
    apt update -y
    apt install -y ca-certificates curl gnupg lsb-release
    mkdir -p /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/$OS/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    chmod a+r /etc/apt/keyrings/docker.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/$OS $(lsb_release -cs) stable" \
        | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt update -y
    apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
elif [[ "$OS" == "centos" || "$OS" == "rocky" || "$OS" == "almalinux" ]]; then
    yum install -y yum-utils curl
    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    yum install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
else
    echo "ОС $OS не поддерживается!"
    exit 1
fi
echo "Docker установлен."

echo "Установка docker-compose v1..."
if ! command -v docker-compose >/dev/null 2>&1; then
    LATEST=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep tag_name | cut -d '"' -f 4)
    curl -L "https://github.com/docker/compose/releases/download/${LATEST}/docker-compose-$(uname -s)-$(uname -m)" \
         -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
fi
echo "docker-compose v1 установлен."

echo "Запуск Docker..."
systemctl enable docker
systemctl start docker

echo "Добавление пользователя $REAL_USER в группу docker..."
groupadd -f docker
usermod -aG docker "$REAL_USER"
echo "Пользователь $REAL_USER добавлен в docker. Перезайдите в систему."

echo "Проверка:"
docker --version
docker-compose --version || true
docker compose version

echo "Готово!"
