#!/bin/bash
#
# Copyright (c) 2025, Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

set -e

# This script runs inside the MySQL Docker entrypoint (after mysqld is initialized).
# It creates additional databases listed in MYSQL_MULTIPLE_DATABASES.
# During Docker entrypoint initialization, root connects via socket without a password.

if [ -n "${MYSQL_MULTIPLE_DATABASES}" ]; then

  for db in $(echo "${MYSQL_MULTIPLE_DATABASES//,/ }"); do
    echo "Creating database '$db' (if not exists)..."
    mysql -u root -e \
      "CREATE DATABASE IF NOT EXISTS \`${db}\` CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci;"

    if [ -n "${MYSQL_USER}" ] && [ -n "${MYSQL_PASSWORD}" ]; then
      mysql -u root -e \
        "GRANT ALL PRIVILEGES ON \`${db}\`.* TO '${MYSQL_USER}'@'%';"
    fi
    echo "Database '$db' created and privileges granted."
  done

  mysql -u root -e "FLUSH PRIVILEGES;"

fi
