- name: Ensure backup scripts directory is present
  ansible.builtin.file:
    path: "{{ backup_scripts_dir }}"
    state: directory
    mode: "0755"

- name: Ensure backups group exists
  ansible.builtin.group:
    name: backups
    system: true
    state: present

- name: Ensure Restic backups password file is present
  ansible.builtin.copy:
    src: "restic_backups_passwd"
    dest: "{{ backup_restic_password_file }}"
    owner: root
    group: backups
    mode: "0640"

- name: Ensure all backup scripts are present
  ansible.builtin.template:
    src: "{{ item.type }}.backup.sh.j2"
    dest: "{{ backup_scripts_dir }}/{{ item.name }}.backup.sh"
    owner: root
    group: backups
    mode: "0750"
  loop: "{{ backups }}"

- name: Ensure backup users are in the backups group
  ansible.builtin.user:
    name: "{{ item.user }}"
    groups: backups
    append: true
  loop: "{{ backups }}"
  when: item.user is defined

- name: Ensure systemd service unit is present for each backup
  ansible.builtin.template:
    src: "backup.service.j2"
    dest: "/etc/systemd/system/backup-{{ item.name }}.service"
    owner: root
    group: root
    mode: "0644"
  loop: "{{ backups }}"
  notify: Reload systemd

- name: Ensure systemd timer unit is present for each backup
  ansible.builtin.template:
    src: "backup.timer.j2"
    dest: "/etc/systemd/system/backup-{{ item.name }}.timer"
    owner: root
    group: root
    mode: "0644"
  loop: "{{ backups }}"
  notify: Reload systemd

- name: Ensure backup timers are enabled and started
  ansible.builtin.systemd:
    name: "backup-{{ item.name }}.timer"
    enabled: true
    state: started
    daemon_reload: true
  loop: "{{ backups }}"

- name: Remove legacy backup cronjob if present
  ansible.builtin.cron:
    name: "Perform nightly backups"
    state: absent
