---
- name: Fix permisisons of the NFS directory
  ansible.builtin.file:
    owner: root
    group: root
    mode: "0777"
    path: "{{ nfs_fp }}"
    state: directory

- name: Add the NFS server to the fstab
  ansible.builtin.lineinfile:
    line: "{{ nfs_server_ip }}:{{ nfs_fp }} {{ mount_fp }} nfs defaults 0 0"
    path: /etc/fstab

- name: Ensure the mount point directory exists
  ansible.builtin.file:
    path: /mnt/shared
    state: directory
    mode: "0777"

- name: Mount the NFS
  ansible.posix.mount:
    fstype: nfs
    path: "{{ mount_fp }}"
    src: "{{ nfs_server_ip }}:{{ nfs_fp }}"
    state: mounted
  when: nfs_server_ip not in ansible_all_ipv4_addresses

- name: Mount the NFS locally on the NFS server
  when: nfs_server_ip in ansible_all_ipv4_addresses
  block:
    - name: Configure NFS exports for localhost
      ansible.builtin.lineinfile:
        path: /etc/exports
        line: "/exports/shared 127.0.0.1(rw,sync,no_subtree_check,no_root_squash)"
        state: present
    - name: Apply NFS export configuration
      ansible.builtin.command: exportfs -r
      changed_when: true
    - name: Mount the NFS share on the server itself
      ansible.posix.mount:
        fstype: nfs
        path: "{{ mount_fp }}"
        src: "127.0.0.1:{{ nfs_fp }}"
        state: mounted

- name: Symbolic link the shared directory
  ansible.builtin.file:
    src: "{{ mount_fp }}"
    dest: /flash
    state: link
