#!/bin/bash

DATABASE=pos
 
TABLES=$(echo \\dt | psql -U root $DATABASE | grep "^ public" | awk '{print $3}')
  
for TABLE in $TABLES; do 
  echo $TABLE
  echo "SET zero_damaged_pages = on; VACUUM FULL $TABLE; REINDEX TABLE $TABLE" | psql -U root $DATABASE
done

DUMP_FILE="/tmp/$$.dump"

echo "Will dump database to $DUMP_FILE..."

#pg_dump -Fc -U root pos > $DUMP_FILE
pg_dump -U root pos | gzip -9 > $DUMP_FILE

echo "Will restart database..."

/etc/init.d/postgresql stop
sleep 5
/etc/init.d/postgresql start

echo "Will drop database..."
dropdb -U root pos

echo "Will create database..."
createdb -U root pos

echo "Will restore database from $DUMP_FILE..."
#pg_restore -Fc -U root -d pos $DUMP_FILE 2> /dev/null
gunzip < $DUMP_FILE | psql -U root pos

rm -rf $DUMP_FILE

