---
- name: Install btrfs packages
  apt:
    cache_valid_time: 3600
    name:
      - btrfs-progs
      - monitoring-plugins-btrfs
    state: present

- name: Copy btrfs backup script
  copy:
    dest: /usr/local/sbin/btrfs-backup
    group: root
    mode: preserve
    owner: root
    src: btrfs-backup

- name: Install btrfs scrub services and timers
  loop: &loop
    - service
    - timer
  ansible.builtin.template:
    dest: /etc/systemd/system/btrfs_scrub{{ name }}.{{ item }}
    mode: 0o0644
    src: btrfs_scrub.{{ item }}.j2
  vars: &vars
    name: '{{ device|replace("/", "_") }}'
    # yamllint disable rule:line-length
    mountpoint: |-
      {{ (ansible_facts.mounts|selectattr("device", "equalto", device)|first)["mount"] }}
    # yamllint enable rule:line-length
  tags: [scrub]

- name: Enable btrfs scrub timers
  ansible.builtin.systemd:
    enabled: true
    name: btrfs_scrub{{ name }}.timer
    state: started
  vars: *vars
  tags: [scrub]

- name: Install btrfs check services and timers
  loop: *loop
  ansible.builtin.template:
    dest: /etc/systemd/system/btrfs_check{{ name }}.{{ item }}
    mode: 0o0644
    src: btrfs_check.{{ item }}.j2
  vars: *vars

- name: Enable the btrfs check timers
  ansible.builtin.systemd:
    enabled: true
    name: btrfs_check{{ name }}.timer
    state: started
  vars: *vars
