---
- name: Set a fact about the virtualenv on the remote system
  set_fact:
    virtualenv: "{{ ansible_python_interpreter | dirname | dirname }}"
  when:
    - ansible_python_interpreter is defined
    - not ansible_python_interpreter.startswith('/bin/')
    - not ansible_python_interpreter.startswith('/usr/bin/')

- name: Ensure docker SDK for python is installed
  pip:
    name: docker
    state: latest
    extra_args: "{% if docker_upper_constraints_file %}-c {{ docker_upper_constraints_file }}{% endif %}"
    virtualenv: "{{ virtualenv is defined | ternary(virtualenv, omit) }}"
  become: "{{ virtualenv is not defined }}"

- name: Ensure user is in the docker group
  user:
    name: "{{ ansible_facts.user_id }}"
    groups: docker
    append: yes
  register: group_result
  become: True

# After adding the user to the docker group, we need to log out and in again to
# pick up the group membership. We do this by resetting the SSH connection.

- name: Reset connection to activate new group membership
  meta: reset_connection
  when: group_result is changed

- name: Ensure Docker daemon is started
  service:
    name: docker
    state: started
  become: True

- name: Ensure the path for CA file for private registry exists
  file:
    path: "/etc/docker/certs.d/{{ docker_registry }}"
    state: directory
  become: True
  when: docker_registry is not none and docker_registry_ca is not none

- name: Ensure the CA file for private registry exists
  copy:
    src: "{{ docker_registry_ca }}"
    dest: "/etc/docker/certs.d/{{ docker_registry }}/ca.crt"
  become: True
  when: docker_registry is not none and docker_registry_ca is not none
  notify: reload docker service
