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

###############################################################################
# fix-postgresql-db-permissions.sh
# Fixes PostgreSQL database permissions for existing customer databases.
# On PG 15+, the public schema CREATE privilege is revoked by default.
# This script grants explicit schema permissions to database owners.
# Idempotent - safe to run multiple times.
###############################################################################

echo "=== Fixing PostgreSQL database permissions ==="

# Check if PostgreSQL is installed
if [ ! -f /root/.pgpass ]; then
    echo "PostgreSQL not installed (no .pgpass found), skipping."
    exit 0
fi

PG_PASS=$(cut -d: -f5 /root/.pgpass | head -1)
if [ -z "$PG_PASS" ]; then
    echo "Cannot read PostgreSQL password, skipping."
    exit 0
fi

# Check if PostgreSQL container is running
if ! docker ps --filter=name=postgresql --format='{{.Names}}' | grep -q postgresql; then
    echo "PostgreSQL container not running, skipping."
    exit 0
fi

# Determine how to run psql
if command -v psql &>/dev/null; then
    run_psql() {
        PGPASSWORD="$PG_PASS" psql -h 127.0.0.1 -U postgres "$@"
    }
else
    run_psql() {
        docker exec -e PGPASSWORD="$PG_PASS" postgresql psql -U postgres "$@"
    }
fi

# Get all non-template, non-postgres databases and their owners
# Skip databases owned by postgres (those are system/root databases)
DATABASES=$(run_psql -t -A -F'|' -c "
    SELECT d.datname, u.usename
    FROM pg_database d
    JOIN pg_user u ON d.datdba = u.usesysid
    WHERE d.datistemplate = false
    AND d.datname != 'postgres'
    AND u.usename != 'postgres'
" 2>/dev/null || true)

if [ -z "$DATABASES" ]; then
    echo "No user-owned databases found, nothing to fix."
    exit 0
fi

FIXED=0
FAILED=0

while IFS='|' read -r dbname owner; do
    [ -z "$dbname" ] && continue
    echo "Fixing permissions for database '$dbname' (owner: $owner)..."

    # Grant database-level privileges
    run_psql -c "GRANT ALL PRIVILEGES ON DATABASE \"$dbname\" TO \"$owner\";" 2>/dev/null || true

    # Grant schema-level privileges (must connect to the specific database)
    if run_psql -d "$dbname" <<EOSQL 2>/dev/null
GRANT ALL ON SCHEMA public TO "$owner";
GRANT ALL ON ALL TABLES IN SCHEMA public TO "$owner";
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO "$owner";
GRANT ALL ON ALL FUNCTIONS IN SCHEMA public TO "$owner";
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO "$owner";
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO "$owner";
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON FUNCTIONS TO "$owner";
EOSQL
    then
        echo "  Done."
        ((FIXED++)) || true
    else
        echo "  WARNING: Failed to fix permissions for '$dbname'"
        ((FAILED++)) || true
    fi
done <<< "$DATABASES"

echo ""
echo "=== PostgreSQL permission fix complete ==="
echo "Fixed: $FIXED database(s)"
if [ "$FAILED" -gt 0 ]; then
    echo "Failed: $FAILED database(s) - check logs for details"
fi
