---
# file: roles/filebeat/tasks/main.yml

- name: "fix IT-12220"
  ansible.builtin.file:
    state: absent
    path: "{{ item }}"
  loop:
    - "/etc/apt/sources.list.d/artifacts_elastic_co_packages_7_x_apt.list"
    - "/etc/apt/sources.list.d/artifacts_elastic_co_packages_6_x_apt.list"
    - "/etc/apt/sources.list.d/filebeat.list"
    - "/etc/apt/keyrings/filebeat.asc"
  tags: filebeat

- name: "handle apt repository"
  ansible.builtin.import_tasks: apt_repo.yml
  tags: filebeat

- name: "Ensure any version of filebeat is installed"
  ansible.builtin.apt:
    name: filebeat
    update_cache: true
  when: not filebeat_update
  tags: filebeat

- name: "Ensure the LATEST version of filebeat is installed"
  ansible.builtin.apt:
    name: filebeat
    update_cache: true
    state: latest
  when: filebeat_update
  tags: filebeat

- name: "check haproxy presence"
  ansible.builtin.stat:
    path: /etc/haproxy/haproxy.cfg
  register: haproxy_cfg

- name: "expose boolean of haproxy presence"
  ansible.builtin.set_fact:
    haproxy_present: "{{ haproxy_cfg.stat.exists }}"

- name: "check coraza presence"
  ansible.builtin.stat:
    path: /etc/coraza/coraza.conf
  register: coraza_conf

- name: "expose boolean of coraza presence"
  ansible.builtin.set_fact:
    coraza_present: "{{ coraza_conf.stat.exists }}"

- name: "/etc/filebeat/filebeat.yml"
  ansible.builtin.template:
    src: filebeat.yml.j2
    dest: /etc/filebeat/filebeat.yml
    backup: yes
  notify: restart filebeat
  tags: filebeat

- name: "import_tasks: modules.yml"
  ansible.builtin.import_tasks: modules.yml
  tags:
    - filebeat
    - filebeat_modules

- name: "/etc/systemd/system/filebeat.service"
  ansible.builtin.template:
    src: filebeat.service
    dest: /etc/systemd/system/filebeat.service
  notify:
    - systemctl daemon_reload
    - restart filebeat
  tags: filebeat

- name: "make sure the filebeat service is enabled"
  ansible.builtin.systemd_service:
    name: filebeat
    enabled: yes
  tags: filebeat
