From 7f799023d91f98092b4379321a7a63d48db50bcb Mon Sep 17 00:00:00 2001
From: tpiccioli <tommaso.piccioli@isti.cnr.it>
Date: Thu, 16 Sep 2021 23:54:17 +0200
Subject: [PATCH] backup and clean of wal files

---
 files/backuppc_pg_wal.sh                       |  4 ++++
 tasks/postgresql-backup.yml                    |  9 +++++++++
 templates/postgresql_wal_backup_and_removal.j2 | 18 ++++++++++++++++++
 3 files changed, 31 insertions(+)
 create mode 100755 files/backuppc_pg_wal.sh
 create mode 100755 templates/postgresql_wal_backup_and_removal.j2

diff --git a/files/backuppc_pg_wal.sh b/files/backuppc_pg_wal.sh
new file mode 100755
index 0000000..ed29342
--- /dev/null
+++ b/files/backuppc_pg_wal.sh
@@ -0,0 +1,4 @@
+#!/bin/bash
+
+su - postgres -c "/usr/local/sbin/postgresql_wal_backup_and_removal > /var/log/postgresql/wal_removal.log 2>&1"
+
diff --git a/tasks/postgresql-backup.yml b/tasks/postgresql-backup.yml
index e55fba4..5c9bee0 100644
--- a/tasks/postgresql-backup.yml
+++ b/tasks/postgresql-backup.yml
@@ -43,6 +43,15 @@
   when: psql_wal_files_archiving_enabled
   tags: [ 'pg_backup', 'postgresql', 'postgres' ]
 
+- name: Backup script for the postgresql streaming replication database(s)
+  template: src=postgresql_wal_backup_and_removal.j2 dest=/usr/local/sbin/postgresql_wal_backup_and_removal owner=root mode=0744
+  tags: [ 'pg_stream_backup', 'postgresql', 'postgres' ]
+
+- name: backuppc root script for the postgresql streaming replication database(s)
+  copy: src=backuppc_pg_wal.sh dest=/usr/local/sbin/backuppc_pg_wal.sh owner=root mode=0744
+  when: psql_wal_files_archiving_enabled
+  tags: [ 'pg_stream_backup', 'postgresql', 'postgres' ]
+
 - name: authorization file for the psql command
   template: src=pgpass.j2 dest={{ pg_backup_pass_file }} owner=root mode=0600
   tags: [ 'pg_backup', 'postgresql', 'postgres', 'pgpass', 'pg_db' ]
diff --git a/templates/postgresql_wal_backup_and_removal.j2 b/templates/postgresql_wal_backup_and_removal.j2
new file mode 100755
index 0000000..caffc7f
--- /dev/null
+++ b/templates/postgresql_wal_backup_and_removal.j2
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+BASE_BACKUP_DIR={{ psql_base_backup_dir }}
+WAL_ARCHIVES_LOG_DIR={{ psql_wal_archiving_log_dir }}
+WAL_LATEST_BACKUP=
+
+# The base backup dir needs to be empty
+
+rm -f $BASE_BACKUP_DIR/*
+pg_basebackup -F t -z -D $BASE_BACKUP_DIR
+
+cd $WAL_ARCHIVES_LOG_DIR
+WAL_LATEST_BACKUP=$( /bin/ls -1tr *.backup | tail -1 )
+pg_archivecleanup $WAL_ARCHIVES_LOG_DIR $WAL_LATEST_BACKUP
+
+exit $?
+
+