#!/bin/bash
set -e

# 환경 변수에서 DB 이름 가져오기 (기본값 설정)
KRATOS_DB=${KRATOS_DB:-ory_kratos}
HYDRA_DB=${HYDRA_DB:-ory_hydra}
KETO_DB=${KETO_DB:-ory_keto}

# 함수 정의: DB가 없으면 생성
create_db_if_not_exists() {
    local dbname=$1
    if ! psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -lqt | cut -d \| -f 1 | grep -qw "$dbname"; then
        psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
            CREATE DATABASE $dbname;
EOSQL
        echo "Database '$dbname' created."
    else
        echo "Database '$dbname' already exists."
    fi
}

create_db_if_not_exists "$KRATOS_DB"
create_db_if_not_exists "$HYDRA_DB"
create_db_if_not_exists "$KETO_DB"
