# This role installs the docker daemon
---
- name: Remove older docker packages
  apt:
    name:
      - docker
      - docker-engine
      - docker.io
    state: absent

- name: Install source requirements
  apt:
    name:
      - apt-transport-https
      - ca-certificates
      - gnupg2
    state: present

- name: Add Docker's official GPG key
  copy:
    src: docker-debian.asc
    dest: /etc/apt/trusted.gpg.d/docker-debian.asc
    force: yes
    mode: "0644"
    owner: root
    group: root

- name: Add Docker repository
  apt_repository:
    repo: 'deb [arch=amd64] https://download.docker.com/linux/debian {{ ansible_distribution_release }} stable'
    state: present
    filename: docker.list

- name: Install Docker
  apt:
    name:
      - docker-ce
      - docker-ce-cli
      - containerd.io
    update_cache: yes

- name: python-docker is installed
  apt:
    name: python-docker
    state: present
  when: ansible_python_version is version('3', '<')

- name: python3-docker is installed
  apt:
    name: python3-docker
    state: present
  when: ansible_python_version is version('3', '>=')

- name: Copy Docker daemon configuration file
  template:
    src: daemon.json.j2
    dest: /etc/docker/daemon.json
  notify: restart docker

- name: Creating Docker tmp directory
  file:
    path: "{{ docker_tmpdir }}"
    state: directory
    mode: "0644"
    owner: root

- name: Creating Docker TLS directory
  file:
    path: "{{ docker_tls_path }}"
    state: directory
    mode: "0644"
    owner: root
  when: docker_tls_enabled | bool

- name: Copy shellpki utility to Docker TLS directory
  template:
    src: "{{ item }}.j2"
    dest: "{{ docker_tls_path }}/{{ item }}"
    mode: "0744"
  loop:
    - shellpki.sh
    - openssl.cnf
  when: docker_tls_enabled | bool

- name: Check if certs are already created
  stat:
    path: "{{ docker_tls_path }}/certs"
  register: tls_certs_stat

- name: Creating a CA, server key
  command: "{{ docker_tls_path }}/shellpki.sh init"
  when:
    - docker_tls_enabled | bool
    - not tls_certs_stat.stat.isdir
