#!/bin/bash
#
# Script to create a complete dump of a Drupal Postgresql database, keeping two backups at
# the same time, one for yesterday and one for today.
#
# You have to specify the folder where backups have to be saved and the name of
# the database.
# The script uses pg_dump
# Suggestion: indicate the complete path.
# 
# Use as ./backup.sh ~/backupFolder databaseName
#
# Copyright (C) 2014 Riccardo Padovani <riccardo@rpadovani.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>

# Backup directory
DIR=${1}
DBNAME=${2}

# Check if the directory exists, if not, create it
if [ ! -d "$DIR" ]; then
    mkdir "$DIR"
fi

# If there is yesterday backup, then delete it
if [ -f "$DIR"/yesterday.tar.gz ]; then
    rm -f "$DIR"/yesterday.tar.gz
fi

# If there is a backup of today, move it to yesterday
if [ -f "$DIR"/today.tar.gz ]; then
    mv "$DIR"/today.tar.gz "$DIR"/yesterday.tar.gz
fi

# Create the backup
pg_dump "$DBNAME" > "$DIR"/today.sql
tar -cvzf "$DIR"/today.tar.gz "$DIR"/today.sql
# Remove the temp file
rm "$DIR"/today.sql
