#!/bin/sh set -eu set -o pipefail 2>/dev/null || true # Create application databases and ensure ownership and grants (idempotent). : "${GITEA_DB:=giteadb}" : "${GITEA_DB_USER:=gitea}" : "${ODOO_DB:=odoodb}" : "${ODOO_DB_USER:=odoo}" echo "[init] create-databases: gitea_db=${GITEA_DB}, odoo_db=${ODOO_DB}" db_exists() { psql -tAc "SELECT 1 FROM pg_database WHERE datname='$1'" | grep -q 1 || return 1 } db_owner() { psql -tAc "SELECT pg_catalog.pg_get_userbyid(datdba) FROM pg_database WHERE datname='$1'" | tr -d '[:space:]' } create_or_alter_db() { local db="$1"; shift local owner="$1"; shift if db_exists "$db"; then echo "[init] database '$db' already exists" current_owner=$(db_owner "$db") || current_owner="" if [ "$current_owner" != "$owner" ]; then echo "[init] changing owner of '$db' from '$current_owner' to '$owner'" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -c "ALTER DATABASE \"${db}\" OWNER TO \"${owner}\";" fi else echo "[init] creating database '$db' with owner '$owner'" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -c "CREATE DATABASE \"${db}\" OWNER \"${owner}\";" fi echo "[init] granting privileges on ${db} to ${owner}" psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" -c "GRANT ALL PRIVILEGES ON DATABASE \"${db}\" TO \"${owner}\";" } create_or_alter_db "${GITEA_DB}" "${GITEA_DB_USER}" create_or_alter_db "${ODOO_DB}" "${ODOO_DB_USER}" echo "[init] create-databases finished"