---
- 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_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 removing the SSH ControlPersist
# connection.

# NOTE: Ideally we'd use a meta task with the reset_connection option but due
# to https://github.com/ansible/ansible/issues/27520 this does not work
# (checked in Ansible 2.3.2.0). Instead, we use the heavy handed method of
# removing all ansible control sockets. Limitation: if this user is running
# another ansible process, we will kill its connections.
- name: Find persistent SSH connection control sockets
  local_action:
    module: find
    file_type: any
    path: "~/.ansible/cp/"
    patterns: '[a-f0-9]{10}'
    use_regex: True
  register: cp_sockets
  run_once: True
  when:
    - group_result is changed

- name: Drop all persistent SSH connections to activate the new group membership
  local_action:
    module: shell ssh -O stop None -o ControlPath={{ item.path }}
  with_items: "{{ cp_sockets.files }}"
  run_once: True
  when: cp_sockets is not skipped

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

- name: Query docker daemon information
  command: "docker info"
  register: docker_info
  changed_when: False
  until: docker_info is success
  retries: 3
  delay: 5

- name: Fail when loopback-mode containers or images exist
  fail:
    msg: >
      Not configuring docker storage in {{ docker_storage_driver }} mode as
      loopback-backed containers or images exist.
  when:
    - "'Data loop file' in docker_info.stdout or docker_storage_driver not in docker_info.stdout"
    - "'Images: 0' not in docker_info.stdout or 'Containers: 0' not in docker_info.stdout"

- include_tasks: storage.yml
  when: "'Data loop file' in docker_info.stdout or docker_storage_driver not in docker_info.stdout"

- include_tasks: config.yml
