#!/bin/bash
TRACIM_DB_USER='tracim_user'
TRACIM_DB_USER_PASSWORD='tracim_user_password'
TRACIM_DB_NAME='tracim'

# DB_HOST='127.0.0.1'
# DB_PORT='5432'

BUILD_DB_SQL="
CREATE USER ${TRACIM_DB_USER} WITH PASSWORD '${TRACIM_DB_USER_PASSWORD}';
CREATE DATABASE ${TRACIM_DB_NAME};
GRANT ALL PRIVILEGES ON DATABASE ${TRACIM_DB_NAME} TO ${TRACIM_DB_USER};
"

if [ `whoami` != 'postgres' ]; then
  echo "This script is intended to be executed as postgres user."
  exit 1
fi

echo "About to create a new database and user:"
echo "- database: ${TRACIM_DB_NAME}"
echo "- user:     ${TRACIM_DB_USER}"
echo "- password: xxxxxx"
echo
echo "Sleeping 10 seconds."
echo "- stop process by CTRL+C if in doubt."
echo "..."
sleep 10

echo ${BUILD_DB_SQL} | psql
#  -h ${DB_HOST} -p ${DB_PORT}


# IF AN ERROR OCCURS, YOU CAN SIMPLY RESET YOUR POSTGRES SERVER 
# WITH THE FOLLOWING SQL COMMANDS (EXECUTED AS postgres USER):
#
# DROP DATABASE tracim
# DROP OWNED BY tracim_master;
# DROP USER tracim_master;
#
# or more faster: 
#
# psql -c "DROP DATABASE tracim;"
# psql -c "DROP OWNED BY tracim_master;"
# psql -c "DROP USER tracim_master;"

echo
echo "You can now init schema and data by running the following command:"
echo
echo "psql -h 127.0.0.1 -U ${TRACIM_DB_USER} -W ${TRACIM_DB_NAME} < tracim-init-database.new.sql"
echo 
echo "note that you'll be asked for the password"
