#!/bin/bash
set -eu

DATABASE_HOST=${POSTGRES_HOST:-}
DATABASE_PORT=${POSTGRES_PORT:-5432}
DATABASE_SUPERUSER=${POSTGRES_USER:-postgres}
DATABASE_SUPERUSER_PASSWORD=${POSTGRES_PASSWORD:-metamigo}

export PGPASSWORD=$DATABASE_SUPERUSER_PASSWORD

# this script is run under two circumstances: with a local postgres and a remote postgres
# local postgres: we should use the unix domain socket to connect
# remote postgres: we should pass the --host param

HOST_PARAM="--host="
if [[ ! -z ${DATABASE_HOST} ]]; then
	HOST_PARAM="--host=${DATABASE_HOST}"
fi

# wait for postgres process to settle
set +e
echo "pg_isready $HOST_PARAM --username $POSTGRES_USER --dbname template1"
pg_isready "$HOST_PARAM" --username "$POSTGRES_USER" --dbname template1
while ! pg_isready "$HOST_PARAM" --username "$POSTGRES_USER" --dbname template1; do
	echo "$(date) - waiting for database to start"
	sleep 10
done
set -e

echo
echo
echo "Creating the database and the roles"
# We're using 'template1' because we know it should exist. We should not actually change this database.
psql -Xv ON_ERROR_STOP=1 "$HOST_PARAM" --username "$POSTGRES_USER" --dbname template1 <<EOF

CREATE ROLE ${DATABASE_OWNER} WITH LOGIN PASSWORD '${DATABASE_OWNER_PASSWORD}';
GRANT ${DATABASE_OWNER} TO ${DATABASE_SUPERUSER};
CREATE ROLE ${DATABASE_AUTHENTICATOR} WITH LOGIN PASSWORD '${DATABASE_AUTHENTICATOR_PASSWORD}' NOINHERIT;
CREATE ROLE ${DATABASE_VISITOR};
GRANT ${DATABASE_VISITOR} TO ${DATABASE_AUTHENTICATOR};
-- Create database
CREATE DATABASE ${DATABASE_NAME} OWNER ${DATABASE_OWNER};
-- Database permissions
REVOKE ALL ON DATABASE ${DATABASE_NAME} FROM PUBLIC;
GRANT ALL ON DATABASE ${DATABASE_NAME} TO ${DATABASE_OWNER};
GRANT CONNECT ON DATABASE ${DATABASE_NAME} TO ${DATABASE_AUTHENTICATOR};
EOF

echo
echo
echo "Installing extensions into the database"
psql -Xv ON_ERROR_STOP=1 "$HOST_PARAM" --username "$POSTGRES_USER" --dbname "$DATABASE_NAME" <<EOF
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;
CREATE EXTENSION IF NOT EXISTS citext WITH SCHEMA public;
CREATE EXTENSION IF NOT EXISTS pgcrypto WITH SCHEMA public;
CREATE EXTENSION IF NOT EXISTS tablefunc WITH SCHEMA public;
EOF

echo
echo
echo "Creating roles in the database"
psql -Xv ON_ERROR_STOP=1 "$HOST_PARAM" --username "$POSTGRES_USER" --dbname "$DATABASE_NAME" <<EOF
CREATE ROLE app_anonymous;
CREATE ROLE app_user WITH IN ROLE app_anonymous;
CREATE ROLE app_admin WITH IN ROLE app_user;
GRANT app_anonymous TO ${DATABASE_AUTHENTICATOR};
GRANT app_admin TO ${DATABASE_AUTHENTICATOR};
EOF
