#!/bin/sh
#-----------------------------------------------------------------------------
# /var/install/bin/postgresql10-tools-backup
#
# Creation:     2019-04-01 dv
# Last Update:  2021-02-13 08:55:56
#
# Copyright (c) 2023 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/postgresql10

# initialize error counter
error_count="0"

# perform all backups
{
    idx=1
    while [ "${idx}" -le "${POSTGRESQL10_BACKUP_N}" ]
    do
        eval database='${POSTGRESQL10_BACKUP_'${idx}'_DBNAME}'
        eval dbuser='${POSTGRESQL10_BACKUP_'${idx}'_USER}'
        eval maxfiles='${POSTGRESQL10_BACKUP_'${idx}'_MAX}'

        # reduce backup files to configured limit
        if [ "${maxfiles}" -lt "1" ]
        then
            maxfiles='1'
        fi

        # execute backup
        /var/install/bin/postgresql-common-backup-db  \
           --prefix="pgsql10"                         \
           --user="${dbuser}"                         \
           --database="${database}"                   \
           --file-limit="${maxfiles}"                 \
           --mount="${POSTGRESQL10_BACKUP_MOUNT}"     \
           --umount="${POSTGRESQL10_BACKUP_UMOUNT}"   \
           --folder="${POSTGRESQL10_BACKUP_TARGET}"   \
           --port="${POSTGRESQL10_CONNECT_PORT}"  2>&1
        if [ "${?}" -ne "0" ]
        then
            error_count=$((${error_count} + 1))
        fi

        # next backup
        idx=$((${idx} + 1))
    done
} > /tmp/backup-$$.log

# send notification e-mail
if [ -f "/tmp/backup-$$.log" ] && [ -f "/usr/sbin/sendmail" ]
then
    if [ -n "${POSTGRESQL10_BACKUP_NOTIFY}" ] && [ "${error_count}" -gt "0" ]
    then
        full_domain="$(hostname -f)"

        {
            echo "From: PostgreSQL Agent <root@${full_domain}>"
            echo "To: <${POSTGRESQL10_BACKUP_NOTIFY}>"
            echo "Subject: PostgreSQL database backup service on Server '${HOSTNAME}'"
            echo "Mime-Version: 1.0"
            echo "X-Mailer: sendmail PostgreSQL on eisfair"
            echo "Content-Type: text/plain; charset=us-ascii"
            echo "Content-Transfer-Encoding: 8bit"
            echo
            echo
            echo "Dispatched from PostgreSQL Agent on Server '${HOSTNAME}'"
            echo "Current Time: $(/bin/date +%Y-%m-%d-%H:%M:%S)"
            echo
            cat /tmp/backup-$$.log
        } | /usr/sbin/sendmail "${POSTGRESQL10_BACKUP_NOTIFY}"
    fi

    rm -f "/tmp/backup-$$.log"
fi

# return correct exit code
if [ "${error_count}" -gt "0" ]
then
    exit 1
else
    exit 0
fi