#!/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}"

append_current_repo_grants() {
	local target_file="$1"
	cat >> "${target_file}" <<'EOF'

-- Local bootstrap follows the databases owned by this repository. The optional
-- deploy-platform grants can lag a newly added service or be absent in a lightweight
-- checkout; every current owner must still be able to start with the shared local user.
CREATE USER IF NOT EXISTS 'hyapp'@'%' IDENTIFIED BY 'hyapp';
GRANT ALL PRIVILEGES ON hyapp_room.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_user.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_wallet.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_activity.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_lucky_gift.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_cron.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_game.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_robot.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_notice.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_statistics.* TO 'hyapp'@'%';
GRANT ALL PRIVILEGES ON hyapp_admin.* TO 'hyapp'@'%';
FLUSH PRIVILEGES;
EOF
}

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}"
		if [[ "${sql_name}" == "999_local_grants.sql" ]]; then
			append_current_repo_grants "${target_file}"
		fi
		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}"
	if [[ "${sql_name}" == "006_admin_database.sql" ]]; then
		# server/admin owns its migrations but requires the database itself before the
		# process can connect and run them. Keep the fallback minimal and idempotent.
		cat >> "${target_file}" <<'EOF'
CREATE DATABASE IF NOT EXISTS hyapp_admin DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
EOF
	fi
	if [[ "${sql_name}" == "999_local_grants.sql" ]]; then
		append_current_repo_grants "${target_file}"
	fi
	printf 'prepared empty optional mysql init file: %s\n' "${source_file}"
done
