#!/usr/bin/env bash
# Remove SUPERUSER from the application database user
# Run after initial setup: bash scripts/harden-postgres.sh

DB_USER="capakraken"
DB_NAME="capakraken"

echo "Hardening PostgreSQL for $DB_USER..."

# Remove SUPERUSER privilege
docker compose exec -T postgres psql -U postgres -c "ALTER USER $DB_USER NOSUPERUSER;"

# Grant only needed permissions
docker compose exec -T postgres psql -U postgres -d $DB_NAME -c "
  GRANT CONNECT ON DATABASE $DB_NAME TO $DB_USER;
  GRANT USAGE ON SCHEMA public TO $DB_USER;
  GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO $DB_USER;
  GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO $DB_USER;
  ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO $DB_USER;
  ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO $DB_USER;
"

echo "Done. $DB_USER no longer has SUPERUSER."
