#!/bin/bash
set -e

echo "Creating the Metamigo 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 --username "$POSTGRES_USER" --dbname template1 <<EOF
CREATE ROLE ${DATABASE_OWNER} WITH LOGIN PASSWORD '${DATABASE_PASSWORD}';
GRANT ${DATABASE_OWNER} TO ${DATABASE_ROOT_OWNER};
CREATE ROLE ${DATABASE_AUTHENTICATOR} WITH LOGIN PASSWORD '${DATABASE_AUTHENTICATOR_PASSWORD}' NOINHERIT;
CREATE ROLE ${DATABASE_VISITOR};
GRANT ${DATABASE_VISITOR} TO ${DATABASE_AUTHENTICATOR};
-- 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 "Installing extensions into the database"
psql -Xv ON_ERROR_STOP=1 --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 "Creating roles in the database"
psql -Xv ON_ERROR_STOP=1  --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

