#!/bin/bash
#

PG_SERVICE=postgres
PG_USER={{ pg_username }}
PG_DATABASE={{ pg_database }}
PG_DUMPDIR={{ pg_database_dumpdir | default('/var/lib/pgdocker/backup_'+awx_version) }}
PG_TIMESTAMP=`date '+%Y-%m-%d_%H.%M.%S'`
PG_DUMPFILE=${PG_DUMPDIR}/pg_dump_${PG_DATABASE}_${PG_TIMESTAMP}.sql.gz
PG_NB_DAYS=3
#
# /usr/local/bin in den Suchpfad aufnehmen
#
PATH=/usr/local/bin:${PATH}
export PATH

PROG_DIR=`dirname $0`
COMPOSE_DIR={{ awx_composedir }}
COMPOSE_FILES="${COMPOSE_DIR}/{{ awx_compose_name }} ${COMPOSE_DIR}/{{ awx_compose_override_name }}"

#
# Loesche Dump Dateien aelter als 3 Tage
#
echo "Lösche alle Dumps, die älter sind als drei Tage ..."
${PROG_DIR}/HouseKeeping.sh -d ${PG_DUMPDIR} -t ${PG_NB_DAYS} -p '*' -v

[ -d ${PG_DUMPDIR} ] || mkdir ${PG_DUMPDIR}

echo "Stelle sicher, dass der PostgreSQL Container gestartet ist ..."
COMPOSE_OPTIONS="--project-directory ${COMPOSE_DIR} "
for COMPOSE_FILE in ${COMPOSE_FILES}
do
	COMPOSE_OPTIONS="${COMPOSE_OPTIONS} -f ${COMPOSE_FILE}"
done

docker-compose ${COMPOSE_OPTIONS} up -d ${PG_SERVICE}

echo "Erstelle Dump der Datenbanken ..."
docker-compose ${COMPOSE_OPTIONS} exec -T ${PG_SERVICE} pg_dump -U ${PG_USER} ${PG_DATABASE} | gzip >${PG_DUMPFILE}

echo "Größe des Datenbank Dumps: `du -sh ${PG_DUMPFILE}`"
