#!/bin/bash

set -e

DESC="Exportation des bases PostgreSQL"
PG_USER="postgres"

. /usr/share/eole/schedule/config.sh

function RunAs()
{
	user=${1}
	cmd=${2}
	su - ${user} -c "${cmd}"
	return ${?}
}

function RcPwd()
{
    if [ -f /root/.pgpass ]
    then
        PG_PWD=$(cat /root/.pgpass | grep $PG_USER)
        RunAs ${PG_USER} "echo $PG_PWD > ~/.pgpass"
        RunAs ${PG_USER} "chmod 600 ~/.pgpass"
    fi
}



# Defining database host parameter
dbhost=$(CreoleGet container_ip_postgresql)
if [ "$dbhost" = '127.0.0.1' ]
then
	dbhost=''
else
	dbhost="-h $dbhost"
fi

# backup folder
POSTGRESQLSAVDIR=$SAVDIR/postgresql
rm -f $POSTGRESQLSAVDIR/*
mkdir -p $POSTGRESQLSAVDIR

#Store PG_USER password, if exists
RcPwd

# listing databases to backup
locked_templates='template0 template1'
excluded_databases="$(CreoleGet pg_custom_bs_database)"
templates_names=$(RunAs ${PG_USER} "psql -c \"SELECT datname FROM pg_database WHERE datistemplate = '1';\" -t postgres postgres")
db_names=$(RunAs ${PG_USER} "psql -c \"SELECT datname FROM pg_database WHERE datistemplate = '0';\" -t postgres postgres")

# dumping databases
# cluster data first with 00- prefixed name to "ensure" restoration in first place
RunAs ${PG_USER} "pg_dumpall -U postgres $dbhost --globals-only" > ${POSTGRESQLSAVDIR}/00-cluster-wide-data.backup
# templates
for locked_template in $locked_templates
do
    templates_names=${templates_names/$locked_template/}
done
for template_name in $templates_names
do
	RunAs ${PG_USER} "pg_dump -Fc $dbhost -U postgres -w -d $template_name" > ${POSTGRESQLSAVDIR}/${template_name}.backup
done
# databases
for excluded_database in $excluded_databases
do
	db_names=${db_names/$excluded_database/}
done
for db_name in $db_names
do
	RunAs "${PG_USER}" "pg_dump -Fc $dbhost -U postgres -w -d $db_name" > ${POSTGRESQLSAVDIR}/${db_name}.backup
done

RunAs ${PG_USER} "rm -f ~/.pgpass"

exit 0
