---
- name: Install davfs2
  ansible.builtin.dnf:
    name: davfs2
    state: present

- name: Enable user_allow_other in /etc/fuse.conf
  ansible.builtin.lineinfile:
    path: /etc/fuse.conf
    regexp: '^#?\s*user_allow_other'
    line: 'user_allow_other'
    state: present
    create: yes
  register: fuse_conf

- name: Configure davfs2 secrets
  ansible.builtin.lineinfile:
    path: /etc/davfs2/secrets
    line: "{{ storagebox_url }} {{ storagebox_user }} {{ storagebox_password }}"
    create: yes
    mode: "0600"
    owner: root
    group: root

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

- name: Add fstab entry for StorageBox
  ansible.builtin.lineinfile:
    path: /etc/fstab
    line: "{{ storagebox_url }} {{ storagebox_mount_point }} davfs _netdev,auto,user,rw,uid={{ storagebox_uid | default('root') }},gid={{ storagebox_gid | default('root') }}{% if storagebox_dir_mode is defined %},dir_mode={{ storagebox_dir_mode }}{% endif %}{% if storagebox_file_mode is defined %},file_mode={{ storagebox_file_mode }}{% endif %},allow_other 0 0"
    regexp: "^{{ storagebox_url | regex_escape() }}"
    state: present
  register: fstab_entry

- name: Remove stale davfs2 PID file
  ansible.builtin.shell: |
    mountpoint -q {{ storagebox_mount_point }} && exit 0
    rm -f /var/run/mount.davfs/mnt-storagebox.pid
  changed_when: false

- name: Remount StorageBox to apply updated options
  ansible.builtin.shell: |
    if mountpoint -q {{ storagebox_mount_point }}; then
      umount -l {{ storagebox_mount_point }} || true
      sleep 3
    fi
    rm -f /var/run/mount.davfs/mnt-storagebox.pid 2>/dev/null || true
    mount {{ storagebox_mount_point }}
  when: fuse_conf.changed or fstab_entry.changed

- name: Mount StorageBox
  ansible.builtin.shell: |
    mountpoint -q {{ storagebox_mount_point }} && exit 0
    mount {{ storagebox_mount_point }}
  changed_when: false

- name: Create managed StorageBox directories
  ansible.builtin.file:
    path: "{{ item.path }}"
    state: directory
    owner: "{{ item.owner | default(omit) }}"
    group: "{{ item.group | default(omit) }}"
    mode: "{{ item.mode | default('0755') }}"
  loop: "{{ storagebox_managed_directories | default([]) }}"
