---
- name: "Firewalld : Gather status"
  when: agent_apply_firewalld_rule is defined and agent_apply_firewalld_rule in ["force", "auto"]
  become: true
  ansible.builtin.systemd:
    name: firewalld
  register: agent_register_firewalld_service
  tags: [firewall, deploy]

- name: "DEBUG : Print service facts"
  when: agent_apply_firewalld_rule is defined and agent_apply_firewalld_rule in ["force", "auto"]
  ansible.builtin.debug:
    msg: >
      ActiveState: {{ agent_register_firewalld_service.status.ActiveState | default(False) }}
      MainPID: {{ agent_register_firewalld_service.status.MainPID | default(False) }}
      UnitState: {{ agent_register_firewalld_service.status.UnitFileState | default(False) }}
  tags: [never, debug]

- name: "DEBUG : Print rich rule"
  when: >-
    agent_apply_firewalld_rule is defined and agent_apply_firewalld_rule in ["force", "auto"]
    and agent_firewall_allow_from is defined
  ansible.builtin.debug:
    msg: '{{ "rule family=ipv" + agent_internal_ip_version | string + " source address=" + agent_firewall_allow_from | string + " port protocol=tcp port=" + agent_param_listenport
      | string + " accept" if agent_firewall_allow_from is defined else omit }}'
  tags: [never, debug]
  vars:
    agent_internal_ip_version: "{{ 6 if agent_firewall_allow_from is defined and agent_firewall_allow_from | ansible.utils.ipv6 else 4 }}"

- name: "Firewalld : Apply rule"
  become: true
  when: >
    agent_apply_firewalld_rule is defined and agent_apply_firewalld_rule in ["force"]
    or agent_apply_firewalld_rule is defined and agent_apply_firewalld_rule in ["auto"]
      and (
                agent_param_startagents is defined and agent_param_startagents | string != "0"
             or agent_param_startagents is not defined
          )
      and (
                (
                agent_register_firewalld_service.status.ActiveState is defined
                and agent_register_firewalld_service.status.ActiveState == "active"
                )
            or (
                agent_register_firewalld_service.status.UnitFileState is defined
                and agent_register_firewalld_service.status.UnitFileState == "enabled"
                )
          )
  ansible.posix.firewalld:
    port: '{{ agent_param_listenport | string + "/tcp" if agent_firewall_allow_from is not defined else omit }}'
    rich_rule: '{{ "rule family=ipv" + agent_internal_ip_version | string + " source address=" + agent_firewall_allow_from | string + " port protocol=tcp port=" +
      agent_param_listenport | string + " accept" if agent_firewall_allow_from is defined else omit }}'
    zone: "{{ agent_firewalld_zone | default(omit) }}"
    permanent: true
    immediate: '{{ true if agent_register_firewalld_service.status.ActiveState == "active" else false }}'
    state: enabled
  vars:
    agent_internal_ip_version: "{{ 6 if agent_firewall_allow_from is defined and agent_firewall_allow_from | ansible.utils.ipv6 else 4 }}"
  tags: [firewall, deploy]
