#!/bin/bash
###############################################################################
# NocoDB Database Initialization Script
###############################################################################
# This script creates a separate PostgreSQL database for NocoDB's metadata
# to avoid conflicts with Prisma schema management in the main database.
#
# Database: nocodb_meta
# Purpose: Stores NocoDB's internal metadata, views, and configurations
# Runs: Automatically on first PostgreSQL container startup via docker-entrypoint-initdb.d
###############################################################################
set -e

# Create a separate database for NocoDB to avoid Prisma conflicts
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Create NocoDB database if it doesn't exist
    SELECT 'CREATE DATABASE nocodb_meta'
    WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'nocodb_meta')\gexec

    -- Grant all privileges to the main user
    GRANT ALL PRIVILEGES ON DATABASE nocodb_meta TO ${POSTGRES_USER};
EOSQL

echo "NocoDB database 'nocodb_meta' created successfully"
