---

- name: Stat minifirewall config file (before)
  ansible.builtin.stat:
    path: "/etc/default/minifirewall"
  register: minifirewall_before

- name: Check if minifirewall is running
  ansible.builtin.shell:
    cmd: /sbin/iptables -L -n | grep -E "^(DROP\s+udp|ACCEPT\s+icmp)\s+--\s+0\.0\.0\.0\/0\s+0\.0\.0\.0\/0\s*$"
  changed_when: False
  failed_when: False
  check_mode: no
  register: minifirewall_is_running

- ansible.builtin.debug:
    var: minifirewall_is_running
    verbosity: 1

- name: Add some rules at the end of minifirewall file
  ansible.builtin.template:
    src: "{{ item }}"
    dest: "{{ minifirewall_tail_file }}"
    force: "{{ minifirewall_tail_force | bool }}"
    follow: yes
  loop: "{{ query('first_found', templates) }}"
  vars:
    templates:
      - "templates/minifirewall-tail/minifirewall.{{ inventory_hostname }}.tail.j2"
      - "templates/minifirewall-tail/minifirewall.{{ host_group | default('all') }}.tail.j2"
      - "templates/minifirewall-tail/minifirewall.default.tail.j2"
      - "templates/minifirewall.default.tail.j2"
  register: minifirewall_tail_template

- ansible.builtin.debug:
    var: minifirewall_tail_template
    verbosity: 1

- name: source minifirewall.tail at the end of the main file
  ansible.builtin.blockinfile:
    dest: "{{ minifirewall_main_file }}"
    marker: "# {mark} ANSIBLE MANAGED EXTERNAL RULES"
    block: ". {{ minifirewall_tail_file }}"
    insertbefore: EOF
  register: minifirewall_tail_source

- ansible.builtin.debug:
    var: minifirewall_tail_source
    verbosity: 1

- name: Schedule minifirewall restart (legacy)
  ansible.builtin.command:
    cmd: /bin/true
  notify: "restart minifirewall (legacy)"
  when:
    - minifirewall_install_mode == 'legacy'
    - minifirewall_restart_if_needed | bool
    - minifirewall_is_running.rc == 0
    - minifirewall_tail_template is changed

- ansible.builtin.debug:
    var: minifirewall_init_restart
    verbosity: 1
