---
- name: Create StorageBox MongoDB config directory
  ansible.builtin.file:
    path: "{{ storagebox_mount_point }}/db/mongodb-{{ inventory_hostname.split('-')[-1] }}/config"
    state: directory
    mode: '0777'

- name: Create StorageBox PostgreSQL config directory
  ansible.builtin.file:
    path: "{{ storagebox_mount_point }}/db/postgresql-{{ inventory_hostname.split('-')[-1] }}/config"
    state: directory
    mode: '0777'

- name: Deploy mongod.conf to StorageBox
  ansible.builtin.template:
    src: mongod.conf.j2
    dest: "{{ storagebox_mount_point }}/db/mongodb-{{ inventory_hostname.split('-')[-1] }}/config/mongod.conf"
    mode: '0666'

- name: Deploy patroni.yml to StorageBox
  ansible.builtin.template:
    src: patroni.yml.j2
    dest: "{{ storagebox_mount_point }}/db/postgresql-{{ inventory_hostname.split('-')[-1] }}/config/patroni.yml"
    mode: '0666'

- name: Generate MongoDB replica set keyfile on db-01
  when: inventory_hostname == 'iklim-db-01'
  ansible.builtin.shell: |
    openssl rand -base64 756 > {{ storagebox_mount_point }}/db/mongodb-01/config/rs-auth.key
    cp {{ storagebox_mount_point }}/db/mongodb-01/config/rs-auth.key \
       {{ storagebox_mount_point }}/db/mongodb-02/config/rs-auth.key
    cp {{ storagebox_mount_point }}/db/mongodb-01/config/rs-auth.key \
       {{ storagebox_mount_point }}/db/mongodb-03/config/rs-auth.key
    sync
  args:
    creates: "{{ storagebox_mount_point }}/db/mongodb-01/config/rs-auth.key"

- name: Fix MongoDB keyfile permissions on this node
  ansible.builtin.file:
    path: "{{ storagebox_mount_point }}/db/mongodb-{{ inventory_hostname.split('-')[-1] }}/config/rs-auth.key"
    mode: '0400'
    owner: "{{ storagebox_uid }}"
    group: "{{ storagebox_gid }}"
