---
# Install and configure fail2ban with sshd jail.
# Whitelists the WireGuard mesh (fd53::/16) to prevent mesh peers
# from being banned during automated deployments.

- name: Install fail2ban
  apt:
    name: fail2ban
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Deploy jail.local (backend + ban action defaults)
  copy:
    src: jail.local
    dest: /etc/fail2ban/jail.local
    owner: root
    group: root
    mode: "0644"
  notify: restart fail2ban

- name: Deploy jail.d config
  copy:
    dest: /etc/fail2ban/jail.d/mesh.conf
    owner: root
    group: root
    mode: "0644"
    content: |
      [DEFAULT]
      bantime = {{ fail2ban_bantime }}
      findtime = {{ fail2ban_findtime }}
      maxretry = {{ fail2ban_maxretry }}
      ignoreip = {{ fail2ban_ignoreip }}

      [sshd]
      enabled = true
  notify: restart fail2ban

- name: Ensure fail2ban is enabled and running
  systemd:
    name: fail2ban
    enabled: true
    state: started

- name: Verify fail2ban is active
  command: fail2ban-client status
  changed_when: false
  tags: [verify]

- name: Verify sshd jail is running
  command: fail2ban-client status sshd
  changed_when: false
  tags: [verify]
