#!/bin/bash
#
# Name: hs-dump-pgsql
# Author: Michael Hierweck
# Contributors: Michael Hierweck
# License: GNU General Public License (GPL) version 2 or later
# Language: bash
# Dependencies: psql, pg_dump, gzip, secat
# Initial Release: 2011-10-15
# Lastest Release: 2021-03-30
#
# hs-dump-pgsql dumps postgresql databases.
# The master database "postgres" is dumped into /var/backup/pgsql.dmp.gz.
# Other postgresql databases are dumped into the .bak directory of the corresponding package.
# The database dumps are intended to be backuped by the file system backup.
#

cd /tmp

sudo -u postgres pg_dumpall --globals-only --disable-triggers \
|gzip --best \
|secat --user=root --group=root --umask=007 --output=/var/backups/pgsql.dmp.gz

sudo -u postgres psql --no-psqlrc --no-align --field-separator ":" --tuples-only --list \
|cut --delimiter ":" --fields 1 \
|egrep "^[a-z][a-z0-9][a-z0-9][0-9][0-9]_[a-z0-9_]+$" \
|while read DATABASE; do
    PAC="${DATABASE:0:5}"
    DUMP="/home/pacs/${PAC}/.bak/pgsql-${DATABASE}.dmp.gz"
    sudo -u postgres pg_dump --disable-triggers --compress=0 --format=p ${DATABASE} \
    |gzip --best \
    |secat --user=${PAC} --group=${PAC} --umask=077 --output=${DUMP}
done
