#!/bin/bash
# dump database schemas to a new database with specific privileges
# you may want to change the role password with :
# ALTER USER $owner WITH PASSWORD 'new_password';
set -e

origin=bijoe
destination=montpellier3m_bijoe
owner=montpellier3m
schemas=`psql -q -t -c "select schema_name from information_schema.schemata where schema_name LIKE '%eservices%montpellier3m_fr'" bijoe`

psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$owner'" | grep -q 1 || psql -c "CREATE ROLE $owner"

psql -c "select pg_terminate_backend(pid) from pg_stat_activity where datname = '$destination'" >/dev/null
psql -c "DROP DATABASE IF EXISTS $destination" >/dev/null
psql -c "CREATE DATABASE $destination WITH OWNER '$owner'" >/dev/null

psql -c "ALTER ROLE $owner WITH LOGIN" >/dev/null
psql -c "GRANT CONNECT ON DATABASE $destination TO $owner" >/dev/null
psql $destination -c "GRANT SELECT ON ALL TABLES IN SCHEMA public TO $owner" >/dev/null

for schema in $schemas
do
  pg_dump --no-owner --schema $schema $origin | psql $destination >/dev/null
  psql $destination -c "GRANT SELECT ON ALL TABLES IN SCHEMA $schema TO $owner" >/dev/null
  psql $destination -c "GRANT USAGE ON SCHEMA $schema TO $owner" >/dev/null
done
