#!/bin/bash
set -e

echo "Running post_bootstrap script..."

# 创建复制用户和业务用户
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- 创建复制用户
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'replicator') THEN
            CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'replicator@2020';
            RAISE NOTICE 'User replicator created successfully';
        ELSE
            RAISE NOTICE 'User replicator already exists';
        END IF;
    END
    \$\$;

    -- 创建业务用户
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'cqt') THEN
            CREATE ROLE cqt WITH LOGIN PASSWORD 'cqt@2020';
            -- 赋予创建数据库权限
            ALTER ROLE cqt CREATEDB;
            -- 赋予连接权限
            GRANT CONNECT ON DATABASE postgres TO cqt;
            -- 赋予在public schema中的权限
            GRANT USAGE, CREATE ON SCHEMA public TO cqt;
            RAISE NOTICE 'User cqt created successfully';
        ELSE
            RAISE NOTICE 'User cqt already exists';
        END IF;
    END
    \$\$;

    -- 显示所有用户
    \du
EOSQL

echo "Post bootstrap script completed successfully"
