---
- name: Test management of SELinux modules
  hosts: all
  tags:
    # SELinux is not active during container builds, this test covers runtime behaviour
    - tests::booted
  tasks:
    - name: Ensure facts, test variables used by role
      set_fact:
        __selinux_test_facts:
          - distribution
          - distribution_version
    - name: Ensure ansible_facts used by test
      setup:
        gather_subset: min
      when: not ansible_facts.keys() | list |
        intersect(__selinux_test_facts) == __selinux_test_facts
    - name: Execute the role and catch errors
      when: ansible_distribution == "Fedora" or
        (ansible_distribution in ["CentOS", "RedHat", "Rocky"] and
        ansible_distribution_version is version("8.6", ">="))
      vars:
        selinux_modules:
          - {path: "selinux_modules/linux-system-roles-selinux-test-a.pp"}
      block:
        - name: Execute the role
          include_role:
            name: linux-system-roles.selinux
          register: role_result
        - name: Get commit_num file
          set_fact:
            commit_num_file: "{{ __selinux_is_ostree | d(false) |
              ternary('/etc/selinux/targeted/active/commit_num',
                      '/var/lib/selinux/targeted/active/commit_num') }}"
        - name: Get current commit_num
          command: cat {{ commit_num_file | quote }}
          register: commit_num_before
          changed_when: false
        - name: Execute the role
          include_role:
            name: linux-system-roles.selinux
          register: role_result
        - name: Get current commit_num
          command: cat {{ commit_num_file | quote }}
          register: commit_num_after
          changed_when: false
        - name: Check commit numbers
          assert:
            that:
              commit_num_before.stdout == commit_num_after.stdout
      always:
        - name: Cleanup modules
          command: "{{ item }}"
          loop:
            - "semodule -r linux-system-roles-selinux-test-a"
          ignore_errors: true  # noqa ignore-errors
          changed_when: false
