---
- name: "Ensure needed packages"
  become: yes
  package:
    name: pigz

- name: "Create destination backup directory"
  become: yes
  ansible.builtin.file:
    path: '{{ backup_dest_dir }}'
    state: directory
    mode: '0755'
    owner: postgres
    group: postgres

- name: "Block: gpg stuff"
  become: yes
  become_user: postgres
  block:
    - name: Create temp dir
      ansible.builtin.tempfile:
        state: directory
        suffix: gitcheckout
        path: /tmp
      register: tempdir

    - name: "Checkout repo for gpg communication-keys"
      ansible.builtin.git:
        repo: 'https://{{ gituser | default("gitea-admin") | urlencode }}:{{ gitea_admin_password | urlencode }}@{{ stage }}-gitea-01.{{ domain }}/gitea-admin/communication-keys.git'
        dest: '{{ tempdir.path }}'
        version: master

# there is no ansible gpg module already in place
# linting violation needs to be whitelisted
    - name: "Importing stage specific automation gpg-key" # noqa command-instead-of-shell
      shell: 'gpg --import {{ tempdir.path }}/smardigo_automation_{{ stage }}.gpg.pub'

# there is no ansible module already in place for (pg_basebackup|gpg)
# so using shell module
- name: "Creating pg_basebackup ... + doing async check if successful or not"
  become: yes
  become_user: postgres
  vars:
    backup_file: '{{ backup_dest_dir }}/basebackup_{{ current_date_time }}.tar.gz'
  shell: |
      set -o pipefail
      /usr/bin/pg_basebackup -Ft -X fetch -D - | nice -n {{ postgres_backup_niceness_pigz | default(8) }} pigz -p 2 > {{ backup_file }} && \
      nice -n {{ postgres_backup_niceness_gpg | default(10) }} gpg --encrypt --recipient "smardigo automation {{ stage | upper }}" --trust-model always {{ backup_file }} && \
      rm {{ backup_file }}
  args:
    executable: /bin/bash
  async: 3600 # allows duration for task up to 3600sec
  poll: 30 # rechecks every 30sec if task has finished yet
  changed_when: false

# just to make it easier to detect potential failures.
# maybe: can be removed later
- name: "Create STATUS file for successful backup"
  become: yes
  file:
    path: '{{ backup_status_file }}_{{ current_date_time }}'
    state: touch
    mode: '0644'
    owner: postgres
    group: postgres

- name: "Prepare backup dir..."
  become: yes
  ansible.builtin.file:
    path: '{{ backup_dest_dir }}'
    owner: '{{ backupuser_user_name }}'
    group: '{{ backupuser_user_name }}'
    recurse: yes
