---
- name: create mongodb group
  group:
    name: "{{ mongodb_user }}"
    state: present

- name: create mongodb user
  user:
    name: "{{ mongodb_user }}"
    group: "{{ mongodb_user }}"
    state: present

# Workaround because default(omit) is not working. At least in Ansible 2.8.

- name: set mongodb gid
  group:
    name: "{{ mongodb_user }}"
    gid: "{{ mongodb_gid }}"
    state: present
  when: mongodb_gid is defined

- name: set mongodb uid
  user:
    name: "{{ mongodb_user }}"
    uid: "{{ mongodb_uid }}"
    group: "{{ mongodb_user }}"
    state: present
  when: mongodb_uid is defined

- name: Create keyFile
  copy:
    dest: "{{ mongodb_security_keyfile }}"
    content: "{{ mongodb_keyfile_content }}"
    owner: "{{ mongodb_user }}"
    group: "root"
    mode: 0600
  when: mongodb_replication_replset | length > 0

- name: Create log dir if missing
  file:
    state: directory
    dest: "{{ mongodb_systemlog_path|dirname }}"
    owner: "{{ mongodb_user }}"
    group: "{{ mongodb_user }}"
    mode: 0755
  when: mongodb_systemlog_destination == "file"

- name: Check than logfile exists
  stat: path={{ mongodb_systemlog_path }}
  register: logfile_stat
  when: mongodb_systemlog_destination == "file"

- name: Create log if missing
  file:
    state: touch
    dest: "{{ mongodb_systemlog_path }}"
    owner: "{{ mongodb_user }}"
    group: "{{ mongodb_user }}"
    mode: 0644
  when: ( mongodb_systemlog_destination == "file"
        and logfile_stat is defined
        and not logfile_stat.stat.exists )

- name: Ensure dbpath directory
  file:
    path: "{{ mongodb_storage_dbpath }}"
    state: directory
    owner: "{{ mongodb_user }}"
    group: "{{ mongodb_user }}"
    setype: 'mongod_var_lib_t'
    recurse: true
    follow: true

- name: Configure mongodb
  template:
    src: mongod.conf.j2
    dest: /etc/mongod.conf
    backup: true
    owner: root
    group: root
    mode: 0644
  notify:
    - mongodb restart
    - wait when mongodb is started

- name: Flush all handlers at this point
  meta: flush_handlers
