---

- name: "Ensure {{ apt_keyring_dir }} directory exists"
  file:
    path: "{{ apt_keyring_dir }}"
    state: directory
    mode: "755"
    owner: root
    group: root

- name: Add Fluentd GPG key
  ansible.builtin.copy:
    src: treasuredata.asc
    dest: "{{ apt_keyring_dir }}/treasuredata.asc"
    force: true
    mode: "0644"
    owner: root
    group: root
  tags:
    - packages
    - fluentd

- name: Add Treasuredata repository (Debian <12)
  ansible.builtin.apt_repository:
    repo: "deb [signed-by={{ apt_keyring_dir }}/treasuredata.asc] http://packages.treasuredata.com/3/debian/{{ ansible_distribution_release }}/ {{ ansible_distribution_release }} contrib"
    filename: treasuredata
    state: present
    update_cache: yes
  tags:
    - packages
    - fluentd
  when: ansible_distribution_major_version is version('12', '<')

- name: Add Treasuredata repository (Debian >=12)
  ansible.builtin.template:
    src: treasuredata.sources.j2
    dest: /etc/apt/sources.list.d/treasuredata.sources
    state: present
  register: treasuredata_sources
  tags:
    - packages
    - fluentd
  when: ansible_distribution_major_version is version('12', '>=')

- name: Update APT cache
  ansible.builtin.apt:
    update_cache: yes
  when: treasuredata_sources is changed

- name: Fluentd is installed.
  ansible.builtin.apt:
    name: td-agent
    state: present
  tags:
    - fluentd
    - packages

- name: Fluentd is configured.
  ansible.builtin.template:
    src: td-agent.conf.j2
    dest: "{{ fluentd_conf_path }}"
    mode: "0644"
  notify: "restart fluentd"
  tags:
    - fluentd

- name: Fluentd is running and enabled on boot.
  ansible.builtin.systemd:
    name: td-agent
    enabled: yes
    state: started
  tags:
    - fluentd

- name: NRPE check is configured
  ansible.builtin.lineinfile:
    path: /etc/nagios/nrpe.d/evolix.cfg
    line: 'command[check_fluentd]=/usr/lib/nagios/plugins/check_tcp -p {{ fluentd_port }}'
  notify: "restart nagios-nrpe-server"
  tags:
    - fluentd
    - nrpe
