---

- name: is Munin present ?
  ansible.builtin.stat:
    path: /etc/munin/plugin-conf.d/munin-node
  check_mode: no
  register: munin_node_plugins_config

- name: Munin plugins are present and configured
  block:

    - name: Disable Dovecot plugin
      ansible.builtin.file:
        path: /etc/munin/plugins/dovecot
        state: absent

    - name: Remove old Dovecot plugin conf
      ansible.builtin.file:
        path: "/etc/munin/plugin-conf.d/{{ item }}"
        state: absent
      loop:
        - dovecot
        - z-evolinux-dovecot

    - name: "Remount /usr if needed"
      ansible.builtin.include_role:
        name: remount-usr

    - name: Ensures /usr/local/lib/munin/plugins/ dir exists
      ansible.builtin.file:
        path: "/usr/local/lib/munin/plugins/"
        state: directory
        mode: "0755"

    - name: Install dovecot1 plugin
      # Original from https://github.com/munin-monitoring/contrib/blob/master/plugins/dovecot/dovecot1
      ansible.builtin.copy:
        src: munin_plugin_dovecot1
        dest: /usr/local/lib/munin/plugins/dovecot1
        mode: "0755"

    - name: Install dovecot_stats_ plugin
      # Modified from https://github.com/munin-monitoring/contrib/blob/master/plugins/dovecot/dovecot_stats_
      ansible.builtin.copy:
        src: munin_plugin_dovecot_stats_
        dest: /usr/local/lib/munin/plugins/dovecot_stats_
        mode: "0755"
      tags: dovecot_stats_

    - name: Copy Munin config
      ansible.builtin.copy:
        src: munin_plugins.conf
        dest: /etc/munin/plugin-conf.d/zzz-dovecot
        mode: '0644'
      notify: restart munin-node

    - name: Enable dovecot1 plugin
      ansible.builtin.file:
        src: "/usr/local/lib/munin/plugins/dovecot1"
        dest: "/etc/munin/plugins/dovecot1"
        state: link
      when: not ansible_check_mode

    - name: Enable wildcard dovecot_stats_ plugin for all domains
      ansible.builtin.file:
        src: "/usr/local/lib/munin/plugins/dovecot_stats_"
        dest: "/etc/munin/plugins/dovecot_stats_global"
        state: link
      when: not ansible_check_mode
      tags: dovecot_stats_

  when: munin_node_plugins_config.stat.exists

