---
- name: Ensure restic is installed
  ansible.builtin.apt:
    pkg:
      - restic
  become: true

- name: Write password file
  ansible.builtin.copy:
    dest: /root/restic_password
    mode: "0700"
    content: "{{ repo_password }}"
  become: true

- name: See if already initialized
  ansible.builtin.shell:
    cmd: "restic -r '{{ restic_backup_repo_string }}' init --password-file /root/restic_password"
  failed_when: false
  become: true

- name: Register crontab entry
  ansible.builtin.cron:
    name: "{{ cron_file_name }}"
    cron_file: "{{ cron_file_name }}"
    state: present
    job: "restic -r '{{ restic_backup_repo_string }}' backup {{ directories_to_backup | join(' ') }} --password-file /root/restic_password; restic -r '{{ restic_backup_repo_string }}' forget --keep-last 10 --password-file /root/restic_password"
    minute: "0"
    hour: "1"
    user: root
  become: true

- name: Set up mirroring this repo to remote backup
  block:
    - name: Ensure restic is installed
      ansible.builtin.apt:
        pkg:
          - restic
          - cron
      become: true

    - name: Write password to file
      ansible.builtin.copy:
        dest: /root/restic_password
        mode: "0700"
        content: "{{ repo_password }}"
      become: true

    - name: Initialize repo locally
      ansible.builtin.shell:
        cmd: "restic -r /mnt/backup/{{ repo_name }} init --password-file /root/restic_password"
      failed_when: false
      become: true

    - name: Register cronjob for daily remote backup
      ansible.builtin.cron:
        name: "{{ cron_file_name }}"
        cron_file: "{{ cron_file_name }}"
        state: present
        hour: "1"
        minute: "30"
        user: root
        job: "restic -r /mnt/backup/{{ repo_name }} copy --from-repo '{{ restic_remote_backup_repo_string }}' --from-password-file /root/restic_password --password-file /root/restic_password; restic -r /mnt/backup/{{ repo_name }} forget --keep-last 10 --password-file /root/restic_password"

      become: true

  delegate_to: soteria
