#!/bin/bash
# ==================================================
# CREATE MONITORING USER (Secure Version)
# Usuario para monitoreo de la base de datos
# ==================================================

set -e

echo "==> Creating monitoring user..."

# Usar variable de entorno para la contraseña
if [ -z "$MONITOR_DB_PASSWORD" ]; then
    echo "ERROR: MONITOR_DB_PASSWORD no está configurada"
    echo "Por favor, configure MONITOR_DB_PASSWORD en las variables de entorno"
    exit 1
fi

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Crear usuario de monitoreo (solo lectura)
    DO \$\$
    BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'monitor') THEN
            CREATE ROLE monitor WITH LOGIN PASSWORD '${MONITOR_DB_PASSWORD}';
        END IF;
    END
    \$\$;

    -- Otorgar permisos de lectura
    GRANT CONNECT ON DATABASE $POSTGRES_DB TO monitor;
    GRANT USAGE ON SCHEMA public TO monitor;
    GRANT SELECT ON ALL TABLES IN SCHEMA public TO monitor;

    -- Configurar para futuras tablas
    ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO monitor;
EOSQL

echo "==> Monitoring user created!"
