---
# 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

- name: Generate service base name
  set_fact:
    service_base_name: "{{ 'ansible-docker-test-%0x' % ((2**32) | random) }}"

- name: Registering service names
  set_fact:
    service_name: "{{ service_base_name ~ '-1' }}"

- block:
  - name: Make sure we're not already using Docker swarm
    docker_swarm:
      state: absent
      force: true

  - name: Try to get docker_swarm_service_info when docker is not running in swarm mode
    docker_swarm_service_info:
      name: "{{ service_name }}"
    ignore_errors: true
    register: output

  - name: assert failure when called when swarm is not in use or not run on manager node
    assert:
      that:
        - 'output is failed'
        - 'output.msg == "Error running docker swarm module: must run on swarm manager node"'

  - name: Create a Swarm cluster
    docker_swarm:
      state: present
      advertise_addr: "{{ansible_default_ipv4.address | default('127.0.0.1')}}"
    register: output

  - name: Create services
    docker_swarm_service:
      name: "{{ service_name }}"
      image: "{{ docker_test_image_alpine }}"

  - name: Try to get docker_swarm_service_info for a single service
    docker_swarm_service_info:
      name: "{{ service_name }}"
    register: output

  - name: assert reading reading service info
    assert:
      that:
        - 'output.exists == true'
        - 'output.service.ID is string'
        - 'output.service.Spec.Name == service_name'

  - name: Create random name
    set_fact:
      random_service_name: "{{ 'random-service-%0x' % ((2**32) | random) }}"

  - name: Try to get docker_swarm_service_info using random service name as parameter
    docker_swarm_service_info:
      name: "{{ random_service_name }}"
    register: output

  - name: assert reading reading service info
    assert:
      that:
        - 'output.service is none'
        - 'output.exists == false'

  always:
    - name: Remove services
      docker_swarm_service:
        name: "{{ service_name }}"
        state: absent
      ignore_errors: true

    - name: Remove swarm
      docker_swarm:
        state: absent
        force: 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_info 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)
