#!/bin/bash
#
# Script to create a scrubbed version of a pgsql 9.x database dump using a temp database
# as intermediary.
#
# You need a file named 'scrub.sql' with querys to scrub the db
#
# Use as ./sql_scrub_dump.sh dump_file_input.tar.gz dump_file_output.tar.gz
# Of course you need to launch it with a user which has a role to create
# database in Postgresql 
#
# The input and the output dump have to be .tar.gz.
#
# 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/>.

# Some params
local_db='temp_scrub'
dump_input=${1}
dump_output=${2}

# Destroy previous temp database and create a new one
dropdb --if-exists "$local_db"
createdb "$local_db"

# Work in /tmp
cd /tmp

# If there is yesterday backup, then delete it
if [ -f "$dump_output" ]; then
    rm -f "$dump_output"
fi


# Extract the file and import in psql
tar -xOvf "$dump_input" | psql "$local_db"

# Scrub the database
psql "$local_db" < scrub.sql

# Export the db
pg_dump "$local_db" > scrubbed-db.sql
tar -cvzf "$dump_output" scrubbed-db.sql

# Removed temporary files
dropdb "$local_db"
rm -f scrubbed-db.sql
