---

- fail:
    msg: Not compatible with Debian 11 (Bullseye)
  when:
  - ansible_distribution_release == "bullseye" 
  - mongodb_version is version_compare('5.0', '<=')


- name: MongoDB embedded GPG key is absent
  apt_key:
    id: "B8612B5D"
    keyring: /etc/apt/trusted.gpg
    state: absent
  when: _trusted_gpg_keyring.stat.exists

- name: Add MongoDB GPG key
  copy:
    src: "server-{{mongodb_version}}.asc"
    dest: "/etc/apt/trusted.gpg.d/mongodb-server-{{mongodb_version}}.asc"
    force: yes
    mode: "0644"
    owner: root
    group: root

- name: enable APT sources list
  apt_repository:
    repo: "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/{{mongodb_version}} main"
    state: present
    filename: "mongodb-org-{{mongodb_version}}"
    update_cache: yes

- name: Install packages
  apt:
    name: mongodb-org
    update_cache: yes
    state: present
  register: _mongodb_install_package

- name: MongoDB service in enabled and started
  systemd:
    name: mongod
    enabled: yes
    state: started
  when: _mongodb_install_package is changed

- name: install dependency for monitoring
  apt:
    name: python-pymongo
    state: present

- name: Custom configuration
  template:
    src: mongodb_buster.conf.j2
    dest: "/etc/mongod.conf"
    force: "{{ mongodb_force_config | bool | ternary('yes', 'no') }}"
  notify: restart mongod

- name: Configure logrotate
  template:
    src: logrotate_buster.j2
    dest: /etc/logrotate.d/mongodb
    force: yes
    backup: no

- include_role:
    name: evolix/remount-usr

- name: Create plugin directory
  file:
    name: /usr/local/share/munin/
    state: directory
    mode: "0755"

- name: Create plugin directory
  file:
    name: /usr/local/share/munin/plugins/
    state: directory
    mode: "0755"

- name: Munin plugins are present
  copy:
    src: "munin/{{ item }}"
    dest: '/usr/local/share/munin/plugins/{{ item }}'
    force: yes
  loop:
    - mongo_btree
    - mongo_collections
    - mongo_conn
    - mongo_docs
    - mongo_lock
    - mongo_mem
    - mongo_ops
    - mongo_page_faults
  notify: restart munin-node

- name: Enable core Munin plugins
  file:
    src: '/usr/local/share/munin/plugins/{{ item }}'
    dest: /etc/munin/plugins/{{ item }}
    state: link
  loop:
    - mongo_btree
    - mongo_collections
    - mongo_conn
    - mongo_docs
    - mongo_lock
    - mongo_mem
    - mongo_ops
    - mongo_page_faults
  notify: restart munin-node
