---

# Configure and restart minifirewall before starting the VRRP service

- name: Check if a recent minifirewall is present
  ansible.builtin.stat:
    path: /etc/minifirewall.d/
  register: _minifirewall_dir

- ansible.builtin.set_fact:
    minifirewall_restart_handler_name: "{{ minifirewall_restart_if_needed | bool | ternary('restart minifirewall', 'restart minifirewall (noop)') }}"

- name: VRRP output is authorized in minifirewall
  ansible.builtin.blockinfile:
    path: /etc/minifirewall.d/vrrpd
    marker: "## {mark} ANSIBLE MANAGED OUTPUT RULES FOR VRID {{ vrrp_address.id }}"
    block: |
      /sbin/iptables -A OUTPUT -o {{ vrrp_address.interface }} -p 112 -j ACCEPT # Allow VRRP output on {{ vrrp_address.interface }}
    create: yes
    mode: "0600"
    owner: "root"
    group: "root"
  notify: "{{ minifirewall_restart_handler_name }}"
  when:
    - vrrp_manage_minifirewall | bool
    - _minifirewall_dir.stat.exists

- name: VRRP input is authorized in minifirewall
  ansible.builtin.blockinfile:
    path: /etc/minifirewall.d/vrrpd
    marker: "## {mark} ANSIBLE MANAGED INPUT RULES FOR VRID {{ vrrp_address.id }}"
    block: |
      {% if vrrp_address.peers | default([]) | length <= 0 %}
        /sbin/iptables -A INPUT -i {{ vrrp_address.interface }} -d 224.0.0.0/8 -j ACCEPT # Allow VRRP input on {{ vrrp_address.interface }} for VRID {{ vrrp_address.id }}
      {% else %}
        {% for peer in vrrp_address.peers %}
          /sbin/iptables -A INPUT -i {{ vrrp_address.interface }} -s {{ peer }} -d 224.0.0.0/8 -j ACCEPT # Allow VRRP input on {{ vrrp_address.interface }} from {{ peer }} for VRID {{ vrrp_address.id }}
        {% endfor %}
      {% endif %}
    create: yes
    mode: "0600"
    owner: "root"
    group: "root"
  notify: "{{ minifirewall_restart_handler_name }}"
  when:
    - vrrp_manage_minifirewall | bool
    - _minifirewall_dir.stat.exists

- name: Flush handlers to restart minifirewall
  ansible.builtin.meta: flush_handlers
  when:
    - vrrp_manage_minifirewall | bool
    - _minifirewall_dir.stat.exists


# Configure VRRP service

- name: set unit name
  ansible.builtin.set_fact:
    vrrp_systemd_unit_name: "vrrp-{{ vrrp_address.id }}.service"

- name: add systemd unit
  ansible.builtin.template:
    src: vrrp.service.j2
    dest: "/etc/systemd/system/{{ vrrp_systemd_unit_name }}"
    force: true
  register: vrrp_systemd_unit

- name: enable and start systemd unit
  ansible.builtin.systemd:
    name: "{{ vrrp_systemd_unit_name }}"
    daemon_reload: yes
    enabled: yes
    state: "{{ vrrp_address.state }}"
  when:
    - vrrp_systemd_unit is changed
    - not ansible_check_mode
