# SPDX-License-Identifier: MIT
---
# All nodes must have the same number of SBD devices. The role is supposed to
# exit with an error if that's not the case. This test verifies, that the check
# works, when SBD devices are defined in both 'ha_cluster_node_options' variable
# (playbook style) and 'ha_cluster' variable (inventory style).
- name: Test a check SBD devices count matches for all nodes (inventory + play)
  hosts: all
  vars_files: vars/main.yml
  vars:
    ha_cluster_sbd_enabled: true

  tasks:
    # Generate a play variable. Play variables are equal for all nodes.
    # This variable is expected to hold data for all nodes.
    # Number of SBD devices is different for each node.
    - name: Generate SBD devices variable
      set_fact:
        __test_node_options: >-
          {{
            (__test_node_options | d([])) + [{
              'node_name': item,
              'sbd_devices': (
                range(1, ansible_play_hosts_all.index(item) + 2)
                | product(['/tmp/dev/sdx']) | map('reverse') | map('join')
                | list)
              }]
          }}
      loop: "{{ ansible_play_hosts_all }}"

    - name: Run test
      when: ansible_play_hosts_all | length > 1
      tags: tests::verify
      vars:
        # Run the role with the play variable generated above
        ha_cluster_node_options: "{{ __test_node_options }}"
      block:
        - name: Set up test environment
          include_role:
            name: linux-system-roles.ha_cluster
            tasks_from: test_setup.yml

        # Generate an "inventory" variable for each node.
        # Number of SBD devices is the same for all nodes. This is expected to
        # be overriden with the play variable in the role.
        - name: Set SBD devices variable
          set_fact:
            ha_cluster:
              sbd_devices:
                - /tmp/dev/sdx1

        - name: Print set SBD devices (inventory)
          debug:
            var: ha_cluster.sbd_devices

        - name: Print set SBD devices (play)
          debug:
            var: ha_cluster_node_options

        - name: Run the role and check for errors
          block:
            - name: Run the role
              include_role:
                name: linux-system-roles.ha_cluster
          rescue:
            - name: Check errors
              assert:
                that: ansible_failed_result.msg == expected_msg
              run_once: true  # noqa: run_once[task]
              vars:
                expected_msg: >-
                  All nodes must have the same number of SBD devices specified
      always:
        - name: Unset SBD devices variable
          set_fact:
            ha_cluster:
            __test_node_options:

    - name: Message
      debug:
        msg: This test needs two or more nodes
      when: ansible_play_hosts_all | length <= 1
