#!/bin/bash
#
# Backup PostgreSQL cluster from LVM partition
#

VG_NAME="vg"
LV_NAME="sql"
LV_SIZE="4G"

MOUNT_DIR="/var/lib/postgresql/tmp"
PG_VERSION="9.3"
PG_CLUSTER="main"

BACKUP_DIR="/home/backup"

#
# script
#

PATH=/usr/sbin:/usr/bin:/sbin:/bin

DATE=`date +%Y%m%d%H%M%S`
SNAPSHOT="${LV_NAME}_${DATE}"

mkdir -p $BACKUP_DIR
mkdir -p $MOUNT_DIR

echo "Backuping PostgreSQL cluster $PG_VERSION/$PG_CLUSTER from LVM partition $VG_NAME/$LV_NAME"
echo ""

echo "- starting PostgreSQL hot backup"
su -c "psql -c \"SELECT pg_start_backup('$SNAPSHOT');\"" -l postgres

echo "- creating LVM snapshot"
lvcreate -s -L$LV_SIZE -n$SNAPSHOT $VG_NAME/$LV_NAME

echo "- stopping PostgreSQL hot backup"
su -c "psql -c \"SELECT pg_stop_backup();\"" -l postgres

echo "- mounting LVM snapshot"
mkdir -p $MOUNT_DIR
mount /dev/mapper/$VG_NAME-$SNAPSHOT $MOUNT_DIR

echo "- archiving files"
tar czf $BACKUP_DIR/$SNAPSHOT.tar.gz -C $MOUNT_DIR/$PG_VERSION/$PG_CLUSTER .

echo "- cleaning"
umount $MOUNT_DIR
lvremove -f $VG_NAME/$SNAPSHOT

echo ""
echo "Backup $SNAPSHOT done."