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

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

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

- name: Ensure configuration directory is present
  ansible.builtin.file:
    path: '/etc/vieter'
    state: directory
    mode: '0755'

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

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

- name: Ensure Container unit files are present
  ansible.builtin.copy:
    src: "{{ item }}"
    dest: "/etc/containers/systemd/{{ item }}"
    mode: '0644'
    owner: 'root'
    group: 'root'
  loop:
    - 'vieter-server.container'
  register: res

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

- name: Ensure Caddyfile is present
  ansible.builtin.copy:
    src: 'vieter-server.Caddyfile'
    dest: '/etc/caddy/vieter-server.Caddyfile'
    mode: '0644'
    owner: 'root'
    group: 'root'
  notify: 'reload caddy'

- name: Ensure vieter service is enabled
  ansible.builtin.service:
    name: 'vieter-server'
    enabled: true
    state: 'started'
