- name: Fail2ban
  hosts: beepi
  become: true

  tasks:
    - name: Install fail2ban
      ansible.builtin.apt:
        name: fail2ban
        state: present

    - name: Create user
      ansible.builtin.user:
        name: fail2forward
        create_home: true

    - name: Create key
      ansible.builtin.user:
        name: fail2forward
        generate_ssh_key: true
        ssh_key_bits: 2048
        ssh_key_type: ed25519
        ssh_key_file: .ssh/id_rsa
      register: ssh_public_key

    - name: Save public key locally
      ansible.builtin.copy:
        content: "{{ ssh_public_key.ssh_public_key }}"
        dest: ./fail2forward_id_rsa.pub
        mode: '0644'
      delegate_to: localhost
      become: false

    - name: Copy jail.local
      ansible.builtin.template:
        src: jail.local.j2
        dest: /etc/fail2ban/jail.local
        owner: root
        group: root
        mode: '0644'

    - name: Copy forward.conf
      ansible.builtin.template:
        src: forward.conf.j2
        dest: /etc/fail2ban/action.d/forward.conf
        owner: root
        group: root
        mode: '0644'

    - name: Restart fail2ban
      ansible.builtin.service:
        name: fail2ban
        state: restarted
