# SPDX-License-Identifier: MIT
---
- name: Check firewall and SELinux
  when:
    - vpn_manage_firewall or vpn_manage_selinux
    - '"firewalld.service" in ansible_facts.services'
    - ansible_facts.services["firewalld.service"]["state"] == "running"
  block:
    - name: Get firewall service
      command: firewall-cmd --list-services
      register: _result
      changed_when: false

    - name: Ensure 'ipsec' is in the firewalld service list
      assert:
        that:
          - "'ipsec' in _result.stdout"

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

    - name: Check associated selinux ports when vpn_manage_selinux is true
      shell: |-
        set -euo pipefail
        semanage port --list -C | grep ipsecnat_port_t | \
          grep "{{ pair[0] }}" | grep "{{ pair[1] }}"
      changed_when: false
      vars:
        pair: "{{ item.split('/') }}"
      loop: "{{ __ports.stdout.split(' ') }}"
      when: vpn_manage_selinux | bool
