#!/usr/bin/env bash
set -euo pipefail

export PGHOST="$PGHOST"
export PGPORT="$PGPORT"
export PGUSER="$PGUSER"
export PGPASSWORD="$PGPASSWORD"
export PGDATABASE="$PGDATABASE"

# Explanation of pg_dumpall flags:
#
#   --roles-only     only include create, alter, and grant role statements
#
# Explanation of sed substitutions:
#
#   - do not create or alter reserved roles as they are blocked by supautils
#   - explicitly allow altering safe attributes, ie. statement_timeout, pgrst.*
#   - discard role attributes that require superuser, ie. nosuperuser, noreplication
#   - do not alter membership grants by supabase_admin role
pg_dumpall \
    --roles-only \
    --quote-all-identifier \
    --no-role-passwords \
    --no-comments \
| sed -E "s/^CREATE ROLE \"($RESERVED_ROLES)\"/-- &/" \
| sed -E "s/^ALTER ROLE \"($RESERVED_ROLES)\"/-- &/" \
| sed -E "s/ (NOSUPERUSER|NOREPLICATION)//g" \
| sed -E "s/^-- (.* SET \"($ALLOWED_CONFIGS)\" .*)/\1/" \
| sed -E "s/GRANT \".*\" TO \"($RESERVED_ROLES)\"/-- &/" \
| sed -E "${EXTRA_SED:-}" \
| uniq

# Reset session config generated by pg_dump
echo "RESET ALL;"
