# SPDX-License-Identifier: MIT
---
- name: Manage SELinux for postfix ports
  when: postfix_manage_selinux | bool
  block:
    - name: Manage firewall for postfix ports
      when:
        - postfix_manage_firewall | bool
        - ansible_facts['os_family'] == 'RedHat'
        - ansible_facts['distribution_version'] is version('7', '>=')
      block:
        - name: Get the smtp related tcp service ports
          shell: |-
            set -euo pipefail
            ports="$(firewall-cmd --info-service="{{ item }}" | \
              grep -E " +ports: +" | sed -e "s/ *ports: //")" || :
            if [ -z "$ports" ]; then
              include="$(firewall-cmd --info-service="{{ item }}" | \
                awk '/^ +includes:/ {print $2}')" || :
              if [ -n "$include" ]; then
                ports="$(firewall-cmd --info-service="$include" | \
                  grep -E " +ports: +" | sed -e "s/ *ports: //")"
              fi
            fi
            if [ -z "$ports" ]; then
              exit 1
            fi
            echo "$ports"
          register: __ports
          changed_when: false
          loop: "{{ __postfix_smtp_services }}"

        - name: Initialize _postfix_selinux
          set_fact:
            _postfix_selinux: []

        - name: Add the smtp related service ports to _postfix_selinux
          set_fact:
            _postfix_selinux: "{{ _postfix_selinux + [{'ports': _pair[0], 'proto': _pair[1], 'setype': 'smtp_port_t', 'state': 'present', 'local': 'true'}] }}"
          vars:
            _pair: "{{ item.stdout.split('/') | list }}"
          when:
            - _pair | length > 0
          loop: "{{ __ports.results }}"

    - name: "Set hardcoded ports to _postfix_selinux for no firewall or rhel-6 or not redhat"
      set_fact:
        _postfix_selinux:
          - {'ports': 25, 'proto': 'tcp', 'setype': 'smtp_port_t', 'state': 'present', 'local': 'true'}
          - {'ports': 465, 'proto': 'tcp', 'setype': 'smtp_port_t', 'state': 'present', 'local': 'true'}
          - {'ports': 587, 'proto': 'tcp', 'setype': 'smtp_port_t', 'state': 'present', 'local': 'true'}
      when:
        - (not postfix_manage_firewall | bool) or (ansible_facts['os_family'] != 'RedHat') or (ansible_facts['distribution_version'] is version('7', '<'))

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