---

# Add some prerequisites
- name: Installing Docker Prerequisites on {{ ansible_distribution }} {{ ansible_distribution_major_version }}
  apt:
    update_cache: yes
    state: present
    name:
      - apt-transport-https
      - ca-certificates
      - gnupg2
      - software-properties-common

# Add APT GPG key
- name: Adding Docker APT repository key for {{ ansible_distribution }} {{ ansible_distribution_major_version }}
  apt_key: url='https://download.docker.com/linux/debian/gpg' state=present

# Add apt repository
- name: Adding Docker APT repository for {{ ansible_distribution }} {{ ansible_distribution_major_version }}
  apt_repository: repo='deb [arch=amd64] https://download.docker.com/linux/debian bullseye stable' state=present

# Apt update
- name: Updating apt cache
  apt:
    update_cache: yes

# Get exact apt package docker version based on var docker_version
- name: Finding APT Docker Version String for {{ docker_version }}
  shell: "apt-cache madison docker-ce | awk '{ print $3 }' | grep '{{ docker_version }}' | sort | tail -n1"
  register: docker_version_output

# Setting docker version string
- name: Set docker_version_string variable to {{ docker_version_output.stdout }}
  set_fact:
    docker_version_string: "{{ docker_version_output.stdout }}"

# Install docker and docker-compose-plugin
# note that with the version in here it will upgrade docker to this version, it may fail if a newer version is installed
- name: Installing Docker
  apt:
    update_cache: yes
    state: present
    # Tell apt to NOT start docker after install
    policy_rc_d: 101
    name:
      - docker-ce={{ docker_version_string }}
      - docker-ce-cli={{ docker_version_string }}
      - containerd.io
      - docker-buildx-plugin
      - docker-compose-plugin

# Configure docker /etc/docker/daemon.js (notice docker has NOT started yet because of policy_rc_d)
- name: Creating /etc/docker
  file:
    path: /etc/docker
    owner: root
    group: root
    state: directory
- name: Templating /etc/daemon.json
  template:
    src: daemon.json.j2
    dest: /etc/docker/daemon.json
    owner: root
    group: root
    mode: 0644
    backup: yes
  notify: restart docker

# Start docker now that we have copied our custom /etc/docker/daemon.json
- name: Starting docker daemon
  service:
    name: docker
    enabled: yes
    state: started

# Install python-docker (required for ansible docker modules)
- name: Installing python3-docker for {{ ansible_distribution }} {{ ansible_distribution_major_version }}
  apt:
    update_cache: yes
    state: present
    name: python3-docker
