---
- 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 }}"

# Allow DB and etcd ports from within the DB subnet so that:
# - db-02/03 accept WireGuard-masqueraded traffic (src = 10.20.20.11 after NAT on db-01)
# - db-01 handles intra-subnet Patroni/etcd coordination and masquerade return traffic
# WireGuard client direct access to db-01 (src 10.8.0.0/24) is handled by the wireguard role.
- name: Allow DB and etcd ports from DB subnet in firewalld
  ansible.posix.firewalld:
    rich_rule: >-
      rule family="ipv4" source address="10.20.20.0/24"
      port port="{{ item }}" protocol="tcp" accept
    zone: drop
    state: enabled
    permanent: true
    immediate: true
  loop:
    - "5432"
    - "27017"
    - "2379"
