#!/bin/bash

if [  -f /etc/default/pg_backup ] ; then
    . /etc/default/pg_backup
else
    PG_BACKUP_ENABLED=True
    PG_SERVICE=postgresql
    USE_NAGIOS=no
    LOG_DIR=/var/log/postgresql
    LOG_FILE=$LOG_DIR/postgresql-backup.log
    PG_BCK_BIN=/usr/local/sbin/postgresql-backup
fi

# Remote backup performed by duplicity. When active, do not run via cron
if [ -x /etc/cron.daily/duplicity_backup ] ; then
    echo "duplicity backups active. Exiting" > $LOG_FILE
    exit 0
fi

# Remote backup performed by BackupPC. If it is active, do not run via cron
if [ -f /var/log/backuppc.log ] ; then
    TMSTMP=$( date +%s )
    . /var/log/backuppc.log
    LAST_BACKUP_TIME=$( expr $TMSTMP - $BACKUP_TIMESTAMP )
    if [ $LAST_BACKUP_TIME -gt 86400 -a $BACKUP_RESULT == 'OK' ] ; then
        echo "BackupPC is active, doing nothing" > $LOG_FILE
        exit 0
    fi
fi

export PATH="/sbin:/usr/sbin:/usr/local/sbin:$PATH"
PG_SVC=$( service $PG_SERVICE status >/dev/null )
PG_RUNNING=$?

if [ $PG_BACKUP_ENABLED == 'True' ] ; then
    if [ "$PG_RUNNING" -ne "0" -a "$PG_RUNNING" -ne "3" ] ; then
        echo "The postgresql service is not running" > $LOG_FILE
        exit 1
    else
        if [  ! -d $LOG_DIR  ] ; then
            mkdir -p $LOG_DIR
        fi
        $PG_BCK_BIN > $LOG_FILE 2>&1
    fi
else
    echo "Postgresql backups administratively disabled" > $LOG_FILE
fi
    
if [ "${USE_NAGIOS}" == "yes" ] ; then
    N_LOGDIR=/var/log/nagios-checks
    if [  ! -d $N_LOGDIR  ] ; then
	mkdir -p $N_LOGDIR
    fi
fi

exit 0