#!/usr/bin/env bash
set -euo pipefail

# Docker creates a missing bind-mounted file source as a directory. MySQL's
# entrypoint then treats that directory as a SQL input and exits before the
# local database is usable. Keep optional platform SQL behind generated files:
# present sources are copied and executed, absent sources become harmless no-op
# SQL files so lightweight backend checkouts can still start.
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DEPLOY_PLATFORM_ROOT="${DEPLOY_PLATFORM_ROOT:-${PROJECT_ROOT}/../deploy-platform}"
LOCAL_INITDB_DIR="${PROJECT_ROOT}/tmp/mysql/initdb"

OPTIONAL_SQL_FILES=(
	"005_utf8mb4_chinese_support.sql"
	"006_admin_database.sql"
	"007_resource_group_wallet_asset_items.sql"
	"999_local_grants.sql"
)

mkdir -p "${LOCAL_INITDB_DIR}"

for sql_name in "${OPTIONAL_SQL_FILES[@]}"; do
	source_file="${DEPLOY_PLATFORM_ROOT}/deploy/mysql/initdb/${sql_name}"
	target_file="${LOCAL_INITDB_DIR}/${sql_name}"

	if [[ -f "${source_file}" ]]; then
		cp "${source_file}" "${target_file}"
		printf 'prepared optional mysql init file: %s\n' "${source_file}"
		continue
	fi

	printf -- '-- optional mysql init file is absent locally: %s\n' "${source_file}" > "${target_file}"
	printf 'prepared empty optional mysql init file: %s\n' "${source_file}"
done
