---
- name: Install nfs-utils and mdadm
  ansible.builtin.dnf:
    name:
      - nfs-utils
      - mdadm
    state: present

# --- RAID persistence ---

- name: Persist mdadm array configuration
  ansible.builtin.shell:
    cmd: mdadm --detail --scan
  register: mdadm_scan
  changed_when: false

- name: Write /etc/mdadm.conf
  ansible.builtin.copy:
    content: "{{ mdadm_scan.stdout }}\n"
    dest: /etc/mdadm.conf
    mode: '0644'
  notify: Rebuild initramfs

# --- RAID mount ---

- name: Create RAID mount point
  ansible.builtin.file:
    path: "{{ raid_mount }}"
    state: directory
    mode: '0755'

- name: Mount RAID5 array (fstab + immediate)
  ansible.posix.mount:
    src: "UUID={{ raid_uuid }}"
    path: "{{ raid_mount }}"
    fstype: "{{ raid_fstype }}"
    opts: defaults,noatime,nodiratime
    state: mounted
    dump: 0
    passno: 2

# --- Répertoires NFS ---

- name: Create NFS export directories
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: directory
    mode: '0755'
    owner: nobody
    group: nobody
  loop: "{{ nfs_exports }}"

# --- NFS server ---

- name: Deploy /etc/exports
  ansible.builtin.template:
    src: exports.j2
    dest: /etc/exports
    mode: '0644'
  notify:
    - Reload exports
    - Restart nfs-server

- name: Enable and start nfs-server
  ansible.builtin.systemd:
    name: nfs-server
    enabled: true
    state: started

# --- Firewall ---

- name: Allow NFS through firewall (firewalld uniquement, pas nftables)
  ansible.posix.firewalld:
    service: "{{ item }}"
    permanent: true
    state: enabled
    immediate: true
  loop:
    - nfs
    - mountd
    - rpc-bind
  when: ansible_facts.services['firewalld.service'] is defined
        and ansible_facts.services['firewalld.service']['state'] == 'running'
