#!/usr/bin/env bash
# Docker CE + compose plugin from the docker.com apt repo. Adds the
# current user to the `docker` group and enables the daemon at boot.
set -euo pipefail
# shellcheck source=./lib.sh
source "$(cd "$(dirname "$0")" && pwd)/lib.sh"
require_debian
require_not_root

if command -v docker >/dev/null 2>&1 \
   && docker compose version >/dev/null 2>&1; then
  skip "docker + compose plugin already present."
else
  log "Installing Docker CE from docker.com apt repo."

  # GPG key.
  sudo install -m 0755 -d /etc/apt/keyrings
  if [[ ! -f /etc/apt/keyrings/docker.asc ]]; then
    curl -fsSL https://download.docker.com/linux/debian/gpg \
      | sudo tee /etc/apt/keyrings/docker.asc >/dev/null
    sudo chmod a+r /etc/apt/keyrings/docker.asc
  fi

  # Repo definition.
  ARCH="$(dpkg --print-architecture)"
  # shellcheck disable=SC1091
  CODENAME="$(. /etc/os-release && echo "${VERSION_CODENAME}")"
  REPO_LINE="deb [arch=${ARCH} signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian ${CODENAME} stable"

  if [[ -f /etc/apt/sources.list.d/docker.list ]] \
     && grep -qxF "$REPO_LINE" /etc/apt/sources.list.d/docker.list; then
    skip "docker.list already configured for $CODENAME."
  else
    echo "$REPO_LINE" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
    ok "Wrote /etc/apt/sources.list.d/docker.list."
  fi

  sudo apt-get update -qq
  apt_install docker-ce docker-ce-cli containerd.io \
    docker-buildx-plugin docker-compose-plugin
  ok "Docker installed."
fi

# Add user to docker group.
if id -nG "$USER" | grep -qw docker; then
  skip "User $USER already in docker group."
else
  sudo usermod -aG docker "$USER"
  warn "Added $USER to docker group — log out and back in for it to apply."
fi

# Enable docker.service at boot.
if systemctl is-enabled docker.service >/dev/null 2>&1; then
  skip "docker.service already enabled at boot."
else
  sudo systemctl enable --now docker.service
  ok "docker.service enabled and started."
fi
