---
# 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: Registering network name
  set_fact:
    nname_1: "{{ name_prefix ~ '-network-1' }}"
- name: Registering network name
  set_fact:
    dnetworks: "{{ dnetworks + [nname_1] }}"

- block:
  # Overlay networks require swarm initialization before they'll work
  - name: swarm
    docker_swarm:
      state: present
      advertise_addr: "{{ ansible_default_ipv4.address | default('127.0.0.1') }}"

####################################################################
## overlay #########################################################
####################################################################

  - name: overlay
    docker_network:
      name: "{{ nname_1 }}"
      driver: overlay
      driver_options:
        com.docker.network.driver.overlay.vxlanid_list: "257"
    register: overlay_1

  - name: overlay (idempotency)
    docker_network:
      name: "{{ nname_1 }}"
      driver: overlay
      driver_options:
        com.docker.network.driver.overlay.vxlanid_list: "257"
    register: overlay_2

  - name: overlay (change)
    docker_network:
      name: "{{ nname_1 }}"
      driver: bridge
    register: overlay_3

  - name: cleanup network
    docker_network:
      name: "{{ nname_1 }}"
      state: absent
      force: true

  - assert:
      that:
      - overlay_1 is changed
      - overlay_2 is not changed
      - overlay_3 is changed

####################################################################
## ingress #########################################################
####################################################################

  - name: cleanup default swarm ingress network
    docker_network:
      name: ingress
      state: absent

  - name: ingress
    docker_network:
      name: "{{ nname_1 }}"
      driver: overlay
      ingress: true
    register: ingress_1

  - name: ingress (idempotency)
    docker_network:
      name: "{{ nname_1 }}"
      driver: overlay
      ingress: true
    register: ingress_2

  - name: ingress (change)
    docker_network:
      name: "{{ nname_1 }}"
      driver: overlay
      ingress: false
    register: ingress_3

  - name: cleanup network
    docker_network:
      name: "{{ nname_1 }}"
      state: absent
      force: true

  - assert:
      that:
      - ingress_1 is changed
      - ingress_2 is not changed
      - ingress_3 is changed

  always:
  - name: cleanup swarm
    docker_swarm:
      state: absent
      force: true
