#!/bin/bash
#
# (c) 2007 Instituto Superior Técnico
#
# License: GPL-2
#

set -e

PGDUMPALL=/usr/bin/pg_dumpall
BCKDIR=/var/backups/postgres
LOCKFILE=/var/run/postgresql/pgbackup
COUNT=7
VERBOSE=yes

function usage() {
    echo "$0: [--count n | --createdir | -v | -q]"
    echo "--count - number of backups to retain"
    echo "--createdir - create directory for postgresql backups and exit, better if run as root"
}

function message(){
    if [ ${VERBOSE} = yes ] ; then
	echo $*
    fi
}

while [ $# -ge 1 ] ; do
    case $1 in
	--count)
	    COUNT=$2
	    shift
	    shift
	    ;;
	--createdir)
	    if [ ! -d ${BCKDIR} ] ; then
		if egrep "^postgres:" /etc/passwd ; then
		    install --directory --group=postgres --owner=postgres --mode=770 ${BCKDIR}
		else
		    message "postgres user don't exist, not creating directory for backups"
		fi
	    else
		message "Dir allready exist, please check permissions"
		if [ ${VERBOSE} = yes ] ; then
		    ls -aldF ${BCKDIR}
		fi
	    fi
	    shift
	    exit 0
	    ;;
	-v)
	    VERBOSE=yes
	    shift
	    ;;
	-q) 
	    VERBOSE=no
	    shift
	    ;;
	*)
	    echo "unknown options $*"
	    usage
	    exit 1
    esac
done

if [ `id -u -n` != postgres ] ; then
    echo "need to be user postgres"
    exit 2
fi

if [ ! -x ${PGDUMPALL} ] ; then
    #postgres not installed 
    exit 3
fi
    
if [ ! -d ${BCKDIR} ] ; then
    install --directory --group=postgres --owner=postgres --mode=770 ${BCKDIR}
fi


if dotlockfile -l -p -r 5 ${LOCKFILE} ; then
    DATE=`date +%Y%m%d%H%M%S`
    ${PGDUMPALL} > ${BCKDIR}/dumpall
    if ! dotlockfile -t -p -r 5 ${LOCKFILE} ; then
	echo "refreshing lockfile failed"
	exit 1
    fi
    nice -20 savelog -q -m 660 -u postgres -g postgres -c ${COUNT} -C -d -n ${BCKDIR}/dumpall
    if ! dotlockfile -u ${LOCKFILE} ; then
	echo "removing lockfile failed"
	exit 1
    fi
else
    echo "Couldn't get lock, aborting backup"
fi
