---
# We have to copy the local jail before installing the package
# or we risk being jailed by fail2ban

- name: Prepare fail2ban hierarchy
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    owner: root
    group: root
    mode: "0755"
  loop:
    - "/etc/fail2ban"
    - "/etc/fail2ban/filter.d"
    - "/etc/fail2ban/fail2ban.d"
  tags:
    - fail2ban

- ansible.builtin.set_fact:
    fail2ban_ignore_ips: "{{ ['127.0.0.1/8'] | union(fail2ban_default_ignore_ips) | union(fail2ban_additional_ignore_ips) | unique }}"
  tags:
    - fail2ban

- name: local jail is installed
  ansible.builtin.template:
    src: jail.local.j2
    dest: /etc/fail2ban/jail.local
    mode: "0644"
    force: "{{ fail2ban_override_jaillocal }}"
  notify: restart fail2ban
  tags:
    - fail2ban

- name: Include ignoredips update task
  ansible.builtin.include: ip_whitelist.yml
  when: fail2ban_force_update_ignore_ips | bool
  tags:
    - fail2ban

- name: custom filters are installed
  ansible.builtin.copy:
    src: "{{ item }}"
    dest: /etc/fail2ban/filter.d/
    mode: "0644"
  loop:
    - dovecot-evolix.conf
    - sasl-evolix.conf
    - wordpress-soft.conf
    - wordpress-hard.conf
    - roundcube.conf
  notify: restart fail2ban
  tags:
    - fail2ban

- name: package fail2ban is installed
  ansible.builtin.apt:
    name: fail2ban
    state: present
  tags:
    - fail2ban
    - packages

- name: is Munin present ?
  ansible.builtin.stat:
    path: /etc/munin/plugins
  check_mode: no
  register: etc_munin_plugins
  tags:
    - fail2ban
    - munin

- name: is fail2ban Munin plugin available ?
  ansible.builtin.stat:
    path: /usr/share/munin/plugins/fail2ban
  check_mode: no
  register: fail2ban_munin_plugin
  tags:
    - fail2ban
    - munin

- name: Enable Munin plugins
  ansible.builtin.file:
    src: "/usr/share/munin/plugins/fail2ban"
    dest: "/etc/munin/plugins/fail2ban"
    state: link
  notify: restart munin-node
  when:
    - etc_munin_plugins.stat.exists
    - fail2ban_munin_plugin.stat.exists
  tags:
    - fail2ban
    - munin

- name: "Extend dbpurgeage if recidive jail is enabled"
  ansible.builtin.blockinfile:
    dest: /etc/fail2ban/fail2ban.d/recidive_dbpurgeage
    marker: "# {mark} ANSIBLE MANAGED"
    block: |
      [DEFAULT]
      dbpurgeage = {{ fail2ban_recidive_bantime }}
    insertafter: EOF
    create: yes
    mode: "0644"
  notify: restart fail2ban
  when:
    - fail2ban_recidive

- name: Fix dbpurgeage for stretch and buster
  ansible.builtin.include: fix-dbpurgeage.yml
  when:
    - ansible_distribution_release == "stretch" or ansible_distribution_release == "buster"
  tags:
    - fail2ban

- name: Script unban_ip is installed
  ansible.builtin.copy:
    src: unban_ip.sh
    dest: /usr/local/sbin/unban_ip
    mode: '0700'
  tags:
    - fail2ban

