---

- name: Install pgBackRest
  apt:
    name: pgbackrest
    state: present

- name: Create pgBackRest repository
  file:
    path: /var/backups/pgbackrest
    state: directory
    owner: postgres
    group: postgres
    mode: "0750"

- name: Configure pgBackRest
  template:
    src: pgbackrest.conf
    dest: /etc/pgbackrest.conf
    owner: root
    group: postgres
    mode: "0640"

- name: Initialise pgBackRest
  command:
    cmd: pgbackrest stanza-create --stanza=main
    creates: /var/backups/pgbackrest/backup/main
  become: true
  become_user: postgres

- name: Configure pgBackRest Postgres WAL archive
  copy:
    src: wal-archive-pgbackrest.sh
    dest: /etc/postgresql/wal-archive/pgbackrest
    owner: root
    group: postgres
    mode: "0750"

- name: Configure pgBackRest cron env
  cron:
    cron_file: pgbackrest
    user: postgres
    env: true
    name: SHELL
    value: /bin/bash

- name: Configure pgBackRest cron jobs
  cron:
    cron_file: pgbackrest
    weekday: "{{ item.weekday }}"
    hour: "{{ item.hour }}"
    minute: "{{ item.minute }}"
    name: pgbackrest-{{ item.name }}
    user: postgres
    job: >-
      {% if item.sleep %}sleep $(($RANDOM \% 3600)) &&{% endif %}
      pgbackrest backup --stanza=main --type={{ item.type }}
  loop:
    - name: daily
      weekday: 1-6
      hour: 3
      minute: 5
      sleep: true
      type: diff
    - name: weekly
      weekday: 0
      hour: 3
      minute: 5
      sleep: true
      type: full
