---
# Install Docker Engine from Docker's official apt repository.
# The Ubuntu-provided docker.io package is not used — it lags behind upstream.

# --- Prerequisites ---

- name: Install apt transport packages
  ansible.builtin.apt:
    name:
      - ca-certificates
      - gnupg
    state: present
    update_cache: true
  tags: docker

- name: Create /etc/apt/keyrings directory
  ansible.builtin.file:
    path: /etc/apt/keyrings
    state: directory
    mode: "0755"
  tags: docker

- name: Download Docker GPG key
  ansible.builtin.get_url:
    url: https://download.docker.com/linux/ubuntu/gpg
    dest: /etc/apt/keyrings/docker.asc
    mode: "0644"
    force: false
  tags: docker

- name: Add Docker apt repository
  ansible.builtin.apt_repository:
    repo: >-
      deb [arch=amd64 signed-by=/etc/apt/keyrings/docker.asc]
      https://download.docker.com/linux/ubuntu
      {{ ansible_distribution_release }} stable
    filename: docker
    state: present
  tags: docker

# --- Install ---

- name: Install Docker Engine and Compose plugin
  ansible.builtin.apt:
    name:
      - docker-ce
      - docker-ce-cli
      - containerd.io
      - docker-buildx-plugin
      - docker-compose-plugin
    state: present
    update_cache: true
  notify: Restart docker
  tags: docker

# --- Daemon configuration ---

- name: Deploy Docker daemon config
  ansible.builtin.template:
    src: daemon.json.j2
    dest: /etc/docker/daemon.json
    owner: root
    group: root
    mode: "0644"
  notify: Restart docker
  tags: docker

# --- Service ---

- name: Enable and start Docker
  ansible.builtin.service:
    name: docker
    state: started
    enabled: true
  tags: docker

# --- Deploy user access ---

- name: Add deploy user to docker group
  ansible.builtin.user:
    name: "{{ deploy_user }}"
    groups: docker
    append: true
  tags: docker

# --- Shared Traefik network ---

- name: Create shared Traefik Docker network
  community.docker.docker_network:
    name: "{{ traefik_network }}"
    driver: bridge
    state: present
  tags: docker
