---
# Copyright (c) Ansible Project
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# SPDX-License-Identifier: GPL-3.0-or-later

####################################################################
# WARNING: These are designed specifically for Ansible tests       #
# and should not be used as examples of how to write Ansible roles #
####################################################################


# Create random name prefix (for containers, networks, ...)
- name: Create random name prefix
  set_fact:
    name_prefix: "{{ 'ansible-docker-test-%0x' % ((2**32) | random) }}"
    service_names: []
    network_names: []
    config_names: []
    secret_names: []
    volume_names: []

- debug:
    msg: "Using container name prefix {{ name_prefix }}"

# Run the tests
- block:
    - name: Create a Swarm cluster
      docker_swarm:
        state: present
        advertise_addr: "{{ansible_default_ipv4.address | default('127.0.0.1')}}"

    - include_tasks: run-test.yml
      with_fileglob:
        - "tests/*.yml"
      loop_control:
        loop_var: test_name

  always:
    - name: Make sure all services are removed
      docker_swarm_service:
        name: "{{ item }}"
        state: absent
      loop: "{{ service_names }}"
      ignore_errors: true

    - name: Make sure all networks are removed
      docker_network:
        name: "{{ item }}"
        state: absent
        force: true
      loop: "{{ network_names }}"
      ignore_errors: true

    - name: Make sure all configs are removed
      docker_config:
        name: "{{ item }}"
        state: absent
        force: true
      loop: "{{ config_names }}"
      ignore_errors: true

    - name: Make sure all volumes are removed
      docker_volume:
        name: "{{ item }}"
        state: absent
      loop: "{{ volume_names }}"
      ignore_errors: true

    - name: Make sure all secrets are removed
      docker_secret:
        name: "{{ item }}"
        state: absent
        force: true
      loop: "{{ secret_names }}"
      ignore_errors: true

    - name: Make sure swarm is removed
      docker_swarm:
        state: absent
        force: true
      ignore_errors: true
  when: docker_py_version is version('2.0.2', '>=') and docker_api_version is version('1.25', '>=')

- fail: msg="Too old docker / docker-py version to run docker_swarm_service tests!"
  when: not(docker_py_version is version('2.0.2', '>=') and docker_api_version is version('1.25', '>=')) and (ansible_distribution != 'CentOS' or ansible_distribution_major_version|int > 6)
