---
- name: Install fail2ban
  apt:
    name: fail2ban
    state: present
    update_cache: yes

- name: Ensure fail2ban filter directory exists
  file:
    path: /etc/fail2ban/filter.d
    state: directory
    mode: "0755"

- name: Ensure fail2ban jail directory exists
  file:
    path: /etc/fail2ban/jail.d
    state: directory
    mode: "0755"

- name: Ensure traefik log directory exists
  file:
    path: /var/log/traefik
    state: directory
    mode: "0755"
    owner: root
    group: root

- name: Deploy Traefik fail2ban filters
  template:
    src: "{{ item }}"
    dest: "/etc/fail2ban/filter.d/{{ item | basename | regex_replace('\\.j2$', '') }}"
    mode: "0644"
  loop:
    - traefik-auth.conf.j2
    - traefik-404.conf.j2
    - traefik-ratelimit.conf.j2
    - traefik-badreq.conf.j2
  notify: Restart fail2ban

- name: Deploy fail2ban jail configuration
  template:
    src: jail.local.j2
    dest: /etc/fail2ban/jail.d/traefik.local
    mode: "0644"
  notify: Restart fail2ban

- name: Ensure fail2ban is enabled and started
  systemd:
    name: fail2ban
    state: started
    enabled: yes
