#!/bin/bash
set -euo pipefail

# Проверка наличия команды
command_exists() {
  command -v "$1" &> /dev/null
}

# Установка make
install_make() {
  echo "Installing make..."
  sudo apt-get update
  sudo apt-get install -y make
}

# Установка docker
install_docker() {
  echo "Installing Docker..."
  sudo apt-get update
  sudo apt-get install -y \
    ca-certificates \
    curl \
    gnupg \
    lsb-release

  sudo install -m 0755 -d /etc/apt/keyrings
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
    sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

  echo \
    "deb [arch=$(dpkg --print-architecture) \
    signed-by=/etc/apt/keyrings/docker.gpg] \
    https://download.docker.com/linux/ubuntu \
    $(lsb_release -cs) stable" | \
    sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

  sudo apt-get update
  sudo apt-get install -y docker-ce docker-ce-cli containerd.io
}

# Установка Docker Compose v2 (плагин)
install_docker_compose() {
  echo "Installing Docker Compose v2 plugin..."
  DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}
  mkdir -p $DOCKER_CONFIG/cli-plugins
  curl -SL https://github.com/docker/compose/releases/download/v2.27.1/docker-compose-linux-$(uname -m) \
    -o $DOCKER_CONFIG/cli-plugins/docker-compose
  chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose
}

# Проверка make
if ! command_exists make; then
  install_make
else
  echo "make is already installed"
fi

# Проверка docker
if ! command_exists docker; then
  install_docker
else
  echo "docker is already installed"
fi

# Проверка docker compose
if ! docker compose version &> /dev/null; then
  install_docker_compose
else
  echo "docker compose is already installed"
fi

