#!/bin/sh
#
# Postgresql backup script

########################################################################
#                          Start configuration                         #
########################################################################
#
##################
# Authentication #
##################
#
# Postgresql username to perform backups under.
postgresql_username="xxxxxx"

# Postgresql password for the Postgresql username (if required).
postgresql_password="xxxxxx"

# Postgresql hostname to connect to.
postgresql_hostname="localhost"

##################
# Locations      #
##################
#
# Location to place backups.
location_backup_dir="/adresar_zaloh/mujserver"

# Location to place the pg_backup.sh logfile.
location_logfile="/adresar_zaloh/mujserver/dump.log"

# Location of the psql binaries.
location_binaries="/usr/local/pgsql/bin"

##################
# Permissions    #
##################
#
# Permissions for the backup location.
permissions_backup_dir="0755"

# Permissions for the backup files.
permissions_backup_file="0644"

# Permissions for the backup logfile.
permissions_backup_log="0644"

##################
# Other options  #
##################
#
# Databases to exclude from the backup process (separated by a space)
exclusions="template"


# You must comment out the line below before using this script
#echo "You must set all values in the configuration section in this file then run ./pg_backup.sh configtest before using this script" && exit 1
########################################################################
#                          End configuration                           #
########################################################################
#
#################
# Variables     #
#################
#
PGUSER="$postgresql_username"
PGPASSWORD="$postgresql_password"
PATH="$PATH:/bin:/usr/bin"

# Export the variables
export PGUSER PGPASSWORD PATH

# seznam databazi v promenne database
tmp=`echo -n '(';echo -n $exclusions | sed 's/\ /\|/g'; echo -n ')'`
if [ "$exclusions" = "" ]; then
	databases=`$location_binaries/psql -h $postgresql_hostname -U $postgresql_username -q -c "\l" template1 | sed -n 4,/\eof/p | grep -v rows\) | awk {'print $1'}`
else
	databases=`$location_binaries/psql -h $postgresql_hostname -U $postgresql_username -q -c "\l" template1 | sed -n 4,/\eof/p | grep -v rows\) | grep -Ev $tmp | awk {'print $1'}`
fi


# provedeni dumpu vsech databazi
for i in $databases; do

	"$location_binaries/vacuumdb" -z -h $postgresql_hostname -U $postgresql_username $i >/dev/null 2>&1
	"$location_binaries/pg_dump" -F p -d -h $postgresql_hostname $i > "$location_backup_dir/postgresql_database-$i-backup"
	chmod $permissions_backup_file "$location_backup_dir/postgresql_database-$i-backup"
done


exit 1




