#!/bin/bash
###############################################################################
# Gancio Database Initialization Script
###############################################################################
# Creates a separate PostgreSQL database for Gancio event management.
#
# Database: gancio
# Purpose: Stores Gancio events, users, and configuration
# Runs: Automatically on first PostgreSQL container startup via docker-entrypoint-initdb.d
###############################################################################
set -e

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
    -- Create Gancio database if it doesn't exist
    SELECT 'CREATE DATABASE gancio'
    WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'gancio')\gexec

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

echo "Gancio database 'gancio' created successfully"
