#!/bin/sh
#-----------------------------------------------------------------------------
# /var/install/bin/postgresql13-tools-backup-cron
#
# Creation:     2019-03-31 dv
# Last Update:  2023-07-23 09:11:10
#
# Copyright (c) 2024 the eisfair team, team(at)eisfair(dot)org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#-----------------------------------------------------------------------------

#include eislib
. /var/install/include/eislib
. /etc/config.d/postgresql13

touch /tmp/db_backup_log$$
result=0

# backup complete database cluster
{
    if [ "${POSTGRESQL13_BACKUP_CLUSTER}" = "yes" ]
    then
        /var/install/bin/postgresql-common-backup-server  \
           --prefix="pgsql13"                             \
           --user="${POSTGRESQL13_BACKUP_CLUSTER_USER}"   \
           --mount="${POSTGRESQL13_BACKUP_MOUNT}"         \
           --umount="${POSTGRESQL13_BACKUP_UMOUNT}"       \
           --folder="${POSTGRESQL13_BACKUP_TARGET}"       \
           --port="${POSTGRESQL13_CONNECT_PORT}"          \
           --file-limit="${POSTGRESQL13_BACKUP_CLUSTER_MAX}"
    fi
} >> /tmp/db_backup_log$$ 2>&1

if [ "${?}" -ne "0" ]
then
    result=1
fi

# backup individual databases
if [ "${result}" -eq "0" ] && [ "${POSTGRESQL13_BACKUP_DATABASES}" = "yes" ]
then
    idx=1
    while [ "${idx}" -le "${POSTGRESQL13_BACKUP_N}" ]
    do
        eval db_name='${POSTGRESQL13_BACKUP_'${idx}'_DBNAME}'
        eval db_user='${POSTGRESQL13_BACKUP_'${idx}'_USER}'
        eval db_max='${POSTGRESQL13_BACKUP_'${idx}'_MAX}'

        {
            /var/install/bin/postgresql-common-backup-db  \
               --prefix="pgsql13"                         \
               --database="${db_name}"                    \
               --user="${db_user}"                        \
               --mount="${POSTGRESQL13_BACKUP_MOUNT}"     \
               --umount="${POSTGRESQL13_BACKUP_UMOUNT}"   \
               --folder="${POSTGRESQL13_BACKUP_TARGET}"   \
               --port="${POSTGRESQL13_CONNECT_PORT}"      \
               --file-limit="${db_max}"
        } >> /tmp/db_backup_log$$ 2>&1

        if [ "${?}" -ne "0" ]
        then
            result=1
        fi

        idx=$((${idx} + 1))
    done
fi

# send e-mail
if [ "${result}" -ne "0" ] && [ "${POSTGRESQL13_BACKUP_NOTIFY}" != "" ]
then
    /var/install/bin/postgresql-common-sendmail      \
        --receipient="${POSTGRESQL13_BACKUP_NOTIFY}" \
        --sender="postgresql13"                      \
        --subject="postgresql13 backup FAILED!"      \
        --file=/tmp/db_backup_log$$
fi

rm -f /tmp/db_backup_log$$

exit 0