#!/bin/bash
# ============================================================
# docker.sh — Docker container runtime
# ============================================================
# Installs Docker Engine and Docker Compose, enables the Docker
# daemon at boot, and adds the current user to the `docker`
# group so containers can be managed without sudo.
#
# docker          — the Docker daemon + CLI
# docker-compose  — the Compose v2 plugin for multi-container apps
#
# Why not Podman instead?  Podman is the preferred rootless
# alternative (see podman.sh), but Docker is still the most
# widely documented container runtime and some workflows
# (Portainer, legacy scripts, certain CI tools) assume it.
#
# Note: Docker's daemon runs as root, which has security
# implications. The docker group grants equivalent root access;
# this is intentional for developer workstations.
# ============================================================

set -euo pipefail
# Load shared logging helpers from the dotfiles lib
source "$(dirname "${BASH_SOURCE[0]}")/../../lib/logging.sh"

# ── Packages ──────────────────────────────────────────────────────────────────
# docker         : the Docker Engine daemon (dockerd) + CLI client (docker)
# docker-compose : Docker Compose plugin; provides `docker compose` subcommand
log "Installing Docker and Docker Compose..."
sudo pacman -S --noconfirm --needed docker docker-compose

# ── Enable Docker daemon ──────────────────────────────────────────────────────
# docker.service starts the Docker daemon at boot.  Without this, running
# `docker` commands would fail with "Cannot connect to the Docker daemon".
log "Enabling Docker service..."
enable_service docker.service

# ── Add current user to docker group ─────────────────────────────────────────
# By default, only root can communicate with the Docker socket at
# /var/run/docker.sock.  Adding the user to the `docker` group grants
# access without requiring `sudo docker ...` every time.
# The group membership takes effect at the next login (a new login session
# is required to re-evaluate group membership).
log "Adding $USER to docker group..."
sudo usermod -aG docker "$USER"

log "Docker installed. Log out and back in for group membership to take effect."
