# SPDX-License-Identifier: MIT
---
- name: Populate service facts
  service_facts:

- name: Manage SELinux
  when:
    - '"firewalld.service" in ansible_facts.services'
    - ansible_facts.services["firewalld.service"]["state"] == "running"
    - ha_cluster_manage_selinux | bool
  block:
    - name: Set the fence-virt/fence-agents port to _ha_cluster_selinux
      set_fact:
        _ha_cluster_selinux:
          - {'ports': '1229', 'proto': 'tcp', 'setype': 'cluster_port_t',
             'state': 'present', 'local': true}
      when:
        - ansible_facts['architecture'] == 'x86_64'
        - (
            'fence-virt' in ha_cluster_fence_agent_packages
            or
            'fence-virt' in ha_cluster_extra_packages
            or
            'fence-agents-all' in ha_cluster_fence_agent_packages
            or
            'fence-agents-all' in ha_cluster_extra_packages
          )

    - name: Get associated selinux ports
      shell: |-
        set -euo pipefail
        firewall-cmd --info-service=high-availability | \
          egrep " +ports: +" | sed -e "s/ *ports: //"
      register: __ports
      changed_when: false

    - name: Add the high-availability service ports to _ha_cluster_selinux
      set_fact:
        _ha_cluster_selinux: "{{ _ha_cluster_selinux | d([]) +
            [{'ports': _pair[0], 'proto': _pair[1], 'setype': 'cluster_port_t',
              'state': 'present', 'local': true}] }}"
      vars:
        _pair: "{{ item.split('/') }}"
      loop: "{{ __ports.stdout.split(' ') }}"

    - name: Ensure the service and the ports status with the selinux role
      include_role:
        name: fedora.linux_system_roles.selinux
      vars:
        selinux_ports: "{{ _ha_cluster_selinux }}"
