#!/bin/bash
# Dezky PostgreSQL initialization
# Creates databases and users for Authentik and OCIS.
# Passwords come from env vars set in docker-compose.yml.

set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Authentik
    CREATE USER authentik WITH PASSWORD '${AUTHENTIK_DB_PASSWORD}';
    CREATE DATABASE authentik WITH OWNER authentik ENCODING 'UTF8' LC_COLLATE 'C' LC_CTYPE 'C' TEMPLATE template0;
    GRANT ALL PRIVILEGES ON DATABASE authentik TO authentik;

    -- OCIS (reserved for future use; OCIS uses internal storage in dev)
    CREATE USER ocis WITH PASSWORD '${OCIS_DB_PASSWORD}';
    CREATE DATABASE ocis WITH OWNER ocis ENCODING 'UTF8' TEMPLATE template0;
    GRANT ALL PRIVILEGES ON DATABASE ocis TO ocis;
EOSQL

# Grant schema permissions inside each newly created DB
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname authentik <<-EOSQL
    GRANT ALL ON SCHEMA public TO authentik;
EOSQL

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname ocis <<-EOSQL
    GRANT ALL ON SCHEMA public TO ocis;
EOSQL

echo "Dezky PostgreSQL initialization complete."
