#!/bin/bash
# made dump of all databases for all instance of postgresql
# 201505 Sébastien JEAN (aka Petit)
# V1.2

dir_conf_pg="/etc/postgresql/"
date=$(date "+%Y-%m-%d")
path_backup="/var/backups/postgres"
check_nagios="/var/lib/postgresql/backup.status"

if [ -f $check_nagios ]
then
    rm $check_nagios
fi
touch $check_nagios

for i in $(find $dir_conf_pg -maxdepth 1 -mindepth 1 -type d )
do
    path_conf_file="$i/main/postgresql.conf"
    port=$(awk '$1 == "port" && $2 == "=" { print $3 }' $path_conf_file)
    version=`echo $i|cut -d "/" -f4`
    mkdir -p $path_backup/$version/$date/
    cd $path_backup/$version/

    DBLIST=`/usr/lib/postgresql/$version/bin/psql -p $port -U postgres -d postgres -q -t -c 'SELECT datname from pg_database'`
	 if [ $? -ne "0" ]
	 then
				echo "Problème avec l'instance PostgreSql-$version" >> $check_nagios
	 fi

    for d in $DBLIST
    do
	if [[ $d != 'template0' && $d != 'template1' ]]
	then
		/usr/lib/postgresql/$version/bin/pg_dump -p $port -U postgres -Fc --format=p $d | pbzip2 -czq3 > $path_backup/$version/$date/$d.bz2
		if [ $? -ne "0" ]
		then
					echo "Problème avec le dump de $d sur l'instance PostgreSql-$version" >> $check_nagios
		fi
	fi
    done
    find  $path_backup/*/* -maxdepth 2 -type d -mtime +2 -exec rm -rf '{}' \;  > /dev/null 2>&1
done
