---
- name: Add some rules at the end of minifirewall file
  template:
    src: "{{ item }}"
    dest: "{{ minifirewall_tail_file }}"
    force: "{{ minifirewall_tail_force | bool }}"
  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

- debug:
    var: minifirewall_tail_template
    verbosity: 1

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

- debug:
    var: minifirewall_tail_source
    verbosity: 1

- name: restart minifirewall
  # service:
  #   name: minifirewall
  #   state: restarted
  command: /etc/init.d/minifirewall restart
  register: minifirewall_init_restart
  failed_when: "'starting IPTables rules is now finish : OK' not in minifirewall_init_restart.stdout"
  changed_when: "'starting IPTables rules is now finish : OK' in minifirewall_init_restart.stdout"
  when:
    - minifirewall_tail_template is changed
    - minifirewall_restart_if_needed | bool

- name: restart minifirewall (noop)
  meta: noop
  register: minifirewall_init_restart
  failed_when: False
  changed_when: False
  when: not (minifirewall_restart_if_needed | bool)

- debug:
    var: minifirewall_init_restart
    verbosity: 1
