---
# Download latest version of binary
- name: Ensure download directory is present
  ansible.builtin.file:
    path: "/home/debian/webdav/{{ webdav_version }}"
    state: directory
    mode: '0755'

- name: Ensure compressed binary is downloaded
  ansible.builtin.get_url:
    url: "https://github.com/hacdias/webdav/releases/download/v{{ webdav_version }}/linux-arm64-webdav.tar.gz"
    dest: "/home/debian/webdav/{{ webdav_version }}/webdav-{{ webdav_version }}.tar.gz"
  register: res

- name: Ensure binary is decompressed
  ansible.builtin.shell:
    chdir: "/home/debian/webdav/{{ webdav_version }}"
    cmd: "tar --extract --gzip --file webdav-{{ webdav_version }}.tar.gz"
  when: 'res.changed'

- name: Ensure binary is copied to correct location
  ansible.builtin.copy:
    src: "/home/debian/webdav/{{ webdav_version }}/webdav"
    remote_src: true
    dest: '/usr/local/bin/webdav'
    owner: 'root'
    group: 'root'
    mode: '0755'
  when: 'res.changed'
  notify: 'restart webdav'


# Set up system user and data directories
- name: Ensure system group exists
  ansible.builtin.group:
    name: 'webdav'
    gid: 5000
    system: true
    state: present

- name: Ensure system user exists
  ansible.builtin.user:
    name: 'webdav'
    group: 'webdav'
    uid: 5000
    system: true
    create_home: false

- name: Ensure data directory is present
  ansible.builtin.file:
    path: '/mnt/data1/webdav'
    state: directory
    mode: '0755'
    owner: 'webdav'
    group: 'webdav'

- name: Ensure data subvolumes are present
  community.general.btrfs_subvolume:
    name: '/webdav/{{ item }}'
  loop:
    - 'data'

- name: Ensure subvolume permissions are correct
  ansible.builtin.file:
    path: "/mnt/data1/webdav/{{ item }}"
    state: directory
    mode: '0755'
    owner: 'webdav'
    group: 'webdav'
  loop:
    - 'data'


# Set up configuration, backup scripts and systemd service
- name: Ensure configuration directory is present
  ansible.builtin.file:
    path: '/etc/webdav'
    state: directory
    mode: '0755'

- name: Ensure config file is present
  ansible.builtin.template:
    src: 'config.toml.j2'
    dest: '/etc/webdav/config.toml'
    mode: '0644'
    owner: 'root'
    group: 'root'
  notify: 'restart webdav'

- name: Ensure backup scripts are present
  ansible.builtin.copy:
    src: "webdav.{{ item }}.backup.sh"
    dest: "/etc/backups/webdav.{{ item }}.backup.sh"
    owner: 'root'
    group: 'root'
    mode: '0644'
  loop:
    - 'data'

- name: Ensure service file is present
  ansible.builtin.copy:
    src: 'webdav.service'
    dest: '/lib/systemd/system/webdav.service'
    owner: 'root'
    group: 'root'
    mode: '0644'
  register: res

- name: systemd-reload
  ansible.builtin.systemd_service:
    daemon_reload: true
  when: 'res.changed'

- name: Ensure webdav service is enabled
  ansible.builtin.service:
    name: 'webdav'
    enabled: true
