---
- name: Telegraf repository key
  ansible.builtin.apt_key:
    url: https://repos.influxdata.com/influxdata-archive_compat.key
    state: present

- name: Telegraf repository
  ansible.builtin.apt_repository:
    repo: "deb https://repos.influxdata.com/ubuntu {{ ansible_distribution_release }} stable"
    state: present
    filename: telegraf
  register: repo_telegraf

- name: Update cache
  ansible.builtin.apt:
    update_cache: true
  when: repo_telegraf.changed

- name: Telegraf packages
  ansible.builtin.apt:
    name: telegraf
    state: present

- name: Cherche si postfix est présent
  ansible.builtin.stat:
    path: /opt/zimbra/common/sbin/mailq
  register: postfix

- name: Ajoute les groupes nécessaire à l'utilisateur telegraf
  ansible.builtin.user:
    name: telegraf
    groups: zimbra,sudo,postfix,postdrop
  when: postfix.stat.exists

- name: Ajoute les groupes nécessaire à l'utilisateur telegraf
  ansible.builtin.user:
    name: telegraf
    groups: zimbra,sudo
  when: not postfix.stat.exists

- name: Donne le droit a telegraf d'éxecuter les commandes zimbra sans pass
  community.general.sudoers:
    name: zxsuite-telegraf
    user: telegraf
    runas: zimbra
    commands:
      - /opt/zimbra/bin/*

- name: Récupération du secret de LDAP
  ansible.builtin.shell: |
    /opt/zimbra/bin/zmlocalconfig -s zimbra_ldap_password | awk '{ print $3}'
  register: zimbra_ldap_password

- name: Set fact
  ansible.builtin.set_fact:
    zimbra_ldap_password: "{{ zimbra_ldap_password.stdout }}"

- name: Installation des scripts de récupération des données zimbra
  ansible.builtin.copy:
    src: files/{{ item }}
    dest: /etc/telegraf/scripts/
    mode: '0755'
    owner: root
    group: root
  loop:
#    - zimbra_one_per_day.sh
#    - zimbra_one_per_hour.sh
     - recup_info_zimbra
  notify: Reload Telegraf
  tags:
    - shscript

- name: Installation de la configuration générale de telegraf
  ansible.builtin.template:
    src: templates/telegraf.conf.j2
    dest: /etc/telegraf/telegraf.conf
    mode: '0755'
    owner: root
    group: root
  notify: Reload Telegraf

- name: Installation de la configuration spécific zimbra pour telegraf
  ansible.builtin.template:
    src: templates/{{ item }}.j2
    dest: /etc/telegraf/telegraf.d/{{ item }}
    mode: '0644'
    owner: root
    group: root
  loop:
    - zimbra_general.conf
    - zimbra_specific.conf
  notify: Reload Telegraf
