#!/bin/bash
#
CMD=$(basename $0)

set -e
set -u

PRJ=${PRJ:-""}
dblist=$PRJ/etc/dblist
keep=$PRJ/etc/backup_keeps
outdir=$PRJ/backup

purge_old()
{
	local here=$(pwd)
	local files=
	local purge=
	local match="${db}-[0-9][0-9][0-9][0-9]*.pgdump"
	cd $outdir
	files=$(ls -t ${match} ${match}.gz 2>/dev/null || :)
	purge=$(echo "$files" | sed -e "1,${keep}d")

	[ "$purge" == "" ] && {
		cd $here
		return 0
	}

	rm -f $purge
	cd $here
	return 0
}


# (MAIN)

[ "$PRJ" == "" ] && {
	echo "you must set \$PRJ variable to use this command" >&2
	exit 1
}

[ -f $dblist ] || {
	echo "db list file '$dblist' not found, exit" >&2
	exit 1
}

[ -d $outdir ] || {
	mkdir $outdir
	chown openerp:openerp $outdir 2>/dev/null || :
	chmod 770 $outdir
}

if [ -f $keep ]
then
	keep=$(cat $keep)
else
	keep=48
fi

for db in $(cat $dblist)
do
	outfile="$outdir/$db-$(date '+%Y.%m.%d-%H.%M.%S').pgdump"

	cmd="pg_dump --file=$outfile --format=p --oids $db"
	su - -s /bin/bash openerp -c "$cmd"
	gzip $outfile

	purge_old $db
done

exit 0
