#!/bin/bash

export PGUSER=postgres
TEST=`psql <<- EOSQL
   SELECT 1 FROM pg_database WHERE datname='$DB_NAME';
EOSQL`

if [[ $TEST == "1" ]]; then
    echo "$DB_NAME exists. continuing startup."
    # database exists
    # $? is 0
    exit 0
else
echo "Creating $DB_NAME for $DB_USER"
psql <<- EOSQL
   CREATE ROLE $DB_USER WITH LOGIN ENCRYPTED PASSWORD '${DB_PASS}' CREATEDB;
   CREATE DATABASE $DB_NAME WITH OWNER $DB_USER TEMPLATE template0 ENCODING 'UTF8';
   GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
EOSQL

echo "Restoring backup file"

gunzip -f $BACKUP_FILE -c | psql

fi

echo ""
echo "$DB_NAME database created"
