#!/bin/bash

set -eu

DATE=$(date '+%Y%m%d %H%M%S')
TODAY=$(date '+%Y%m%d')
HOSTNAME=$(hostname -s)
STATUS=0
LOGFILE="/data/log/scripts/postgresql-dump-databases.log"
PGSQL_HOST="localhost"
PGSQL_USER="{{ postgresql_backup_user }}"
COMPRESS=false

touch ${LOGFILE}

#
# Fonctions
#

checkNas()
{
    if [ ! -e "${BACKUPDIR}/.mount" ]; then
        echo "${BACKUPDIR} not mounted. Backup aborted." | tee -a ${LOGFILE}
        exit 1
    fi
}

usage()
{
  echo "$0 -r <retention> -d <repertoire> -c (compression)"
  echo "Exemple : /data/scripts/postgresql-dump-full.sh -r 20 -d /nas -c"
}

#
# Main
#

while getopts "hcr:d:" option
do
  case "${option}"
  in
    r)
      RETENTION=${OPTARG};;
    d)
      BACKUPDIR=${OPTARG};;
    c)
      COMPRESS=true;;
    h | *)
      usage
      exit 1;;
  esac
done

echo "Lancement du dump - Retention : ${RETENTION} - Repertoire : ${BACKUPDIR}" | tee -a ${LOGFILE}

mkdir -p "$BACKUPDIR"/postgresqldump/ | tee -a ${LOGFILE}
find "$BACKUPDIR"/postgresqldump/ -mindepth 1 -maxdepth 1 -type f -daystart -mtime +"${RETENTION}" -delete | tee -a ${LOGFILE}

# Ne marche pas quand le backup tourne sur un replica
#echo "[${DATE}] - Granting superuser to ${PGSQL_USER} user" | tee -a ${LOGFILE}
#/usr/bin/su - postgres -c "psql --command 'ALTER USER ${PGSQL_USER} WITH SUPERUSER'" | tee -a ${LOGFILE}

DB_LIST=$(/usr/bin/su - postgres -c "psql --csv --command 'select datname from pg_catalog.pg_database'")
for db in ${DB_LIST} ; do
    if  [ ! "$db" = "datname" ] && [ ! "$db" = "template0" ] ; then
        echo "[${DATE}] - Dumping database : $db" | tee -a ${LOGFILE}
        if [ $COMPRESS = true ] ; then
            /usr/bin/pg_dump -Z gzip -f "${BACKUPDIR}"/postgresqldump/"${TODAY}"-"${HOSTNAME}"-"${db}".gz -U "${PGSQL_USER}" -w -h "${PGSQL_HOST}" "${db}" | tee -a ${LOGFILE}
            STATUS=${PIPESTATUS[0]}
        else
            /usr/bin/pg_dump -f "${BACKUPDIR}"/postgresqldump/"${TODAY}"-"${HOSTNAME}"-"${db}".sql -U "${PGSQL_USER}" -w -h "${PGSQL_HOST}" "${db}" | tee -a "${LOGFILE}"
            STATUS=${PIPESTATUS[0]}
        fi
        if [ ! ${STATUS} -eq 0 ]; then
            echo "[${DATE}][CRIT] Dump of $db failed" | tee -a ${LOGFILE}
            echo "[${DATE}] - Revoking superuser from ${PGSQL_USER} user" | tee -a ${LOGFILE}
            /usr/bin/su - postgres -c "psql --command 'ALTER USER ${PGSQL_USER} WITH NOSUPERUSER'" | tee -a ${LOGFILE}
            OUTPUT="${OUTPUT} $db"
            break
        fi
    fi
done

# Ne marche pas quand le backup tourne sur un replica
#echo "[${DATE}] - Revoking superuser from ${PGSQL_USER} user" | tee -a ${LOGFILE}
#/usr/bin/su - postgres -c "psql --command 'ALTER USER ${PGSQL_USER} WITH NOSUPERUSER'" | tee -a ${LOGFILE}

STATUS=$?

# output in statusfile for checkmk
echo "$(date +%s)|${STATUS}|Check log file ${LOGFILE}" > /var/tmp/batch."$(basename "$0")"
echo "Fin du dump - Retention : ${RETENTION} - Repertoire : ${BACKUPDIR}" | tee -a ${LOGFILE}
