---
- name: Install packages
  ansible.builtin.package:
    name: "borgmatic"
    state: present

- name: Deploy borgmatic config
  template:
    src: templates/borgmatic-system.yaml
    dest: /etc/borgmatic.d/system.yaml
    owner: root
    group: root
    mode: '0644'

- name: Deploy borgmatic excludes
  template:
    src: templates/borgmatic-excludes
    dest: /etc/borgmatic/excludes
    owner: root
    group: root
    mode: '0644'

- name: SSH Keypair
  openssh_keypair:
    path: /etc/borgmatic/borg_key
    owner: root
    group: root

- name: Get SSH key
  slurp:
    src: /etc/borgmatic/borg_key.pub
  register: remote_key

- name: Deploy borgmatic authorized_key
  template:
    src: templates/borgmatic-auth-key
    dest: /etc/borgmatic/authorized_keys
    owner: root
    group: root
    mode: '0644'
  vars:
    included_content: "{{ remote_key.content | b64decode }}"

- name: Pickup authorized_key
  fetch:
    src: /etc/borgmatic/authorized_keys
    dest: authorized_keys/{{ ansible_fqdn }}
    flat: yes

- name: Setup Backup Cron Job
  ansible.builtin.cron:
    name: "borgmatic"
    minute: 0
    hour: 1
    job: /usr/bin/borgmatic
