#!/bin/bash

DBNAME='<your_db_name>'
CURDATE=`date '+%y%m%d'`
MYNAME=`hostname -s`
PGDATA=/path_to/pgdata
BUDIR=/$DBNAME/backup/$MYNAME
REMDIR=$BUDIR
start_backup ()
{
psql -U postgres postgres <<_QRY_
SELECT pg_start_backup('BACKUP_$CURDATE');
_QRY_
}

base_backup ()
{
tar cvhzf $BUDIR/current/pgdata.tgz $PGDATA
(cd $PGDATA; find . -type l | xargs ls -l > $BUDIR/current/pg-links.lst)

if [ $? -gt 0 ]
  then
    echo "tar of $PGDATA did not complete successfully"
    echo "aborting base backup"
    stop_backup
    exit 2
fi


}

get_tblspcs ()
{
TLIST=$(psql -qt -U postgres postgres <<_QRY_
SELECT spclocation FROM pg_tablespace WHERE spclocation IS NOT NULL AND spclocation > '';
_QRY_
)
}

backup_tblspcs ()
{
  for tdir in $TLIST
  do
	echo "Tarring $tdir"
        tarfile=`basename $tdir.tgz`
        tar cvhfz $BUDIR/current/$tarfile $tdir/

        if [ $? -gt 0 ]
          then
          echo "tar of table spaces did not complete successfully"
          echo "aborting base backup"
          stop_backup
          exit 2
        fi

  done

}

stop_backup ()
{
psql -U postgres postgres <<_QRY_
SELECT pg_stop_backup();
_QRY_
}

###                      MAIN SCRIPT                             ###

if [ "$USER" != "root" ]
  then
    echo "You must be root to execute this script."
    echo "Aborting." 
    exit 1
fi

echo "Initiating db backup"
start_backup

echo "Backuping up pgdata"
base_backup

get_tblspcs
#echo "$TLIST"
#backup_tblspcs

echo "Stopping db backup"
stop_backup

echo "rynch-ing files to dbslave"
rsync -uar $BUDIR/current  dbslave:$REMDIR

exit 0

