#!/usr/bin/env bash

set -euo pipefail

if [ "$#" -ne 1 ]; then
  echo "Usage: bin/mysql_utf8_exec.sh <sql-file>" >&2
  exit 1
fi

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
APP_CONFIG="${PROJECT_ROOT}/ruoyi-admin/src/main/resources/application-dev.yml"
SQL_FILE_INPUT="$1"

if [ ! -f "${APP_CONFIG}" ]; then
  echo "Config file not found: ${APP_CONFIG}" >&2
  exit 1
fi

if [ ! -f "${SQL_FILE_INPUT}" ]; then
  echo "SQL file not found: ${SQL_FILE_INPUT}" >&2
  exit 1
fi

if ! command -v mysql >/dev/null 2>&1; then
  echo "mysql command not found in PATH" >&2
  exit 1
fi

DB_URL="$(awk '/master:/{flag=1;next} flag && /url: jdbc:mysql:\/\//{sub(/.*url: /, ""); print; exit}' "${APP_CONFIG}")"
DB_USER="$(awk '/master:/{flag=1;next} flag && /username:/{sub(/.*username: /, ""); print; exit}' "${APP_CONFIG}")"
DB_PASS="$(awk '/master:/{flag=1;next} flag && /password:/{sub(/.*password: /, ""); print; exit}' "${APP_CONFIG}")"

if [ -z "${DB_URL}" ] || [ -z "${DB_USER}" ]; then
  echo "Failed to parse database config from application-dev.yml" >&2
  exit 1
fi

DB_URL_NO_PREFIX="${DB_URL#jdbc:mysql://}"
DB_HOST_PORT="${DB_URL_NO_PREFIX%%/*}"
DB_NAME="${DB_URL_NO_PREFIX#*/}"
DB_NAME="${DB_NAME%%\?*}"

DB_HOST="${DB_HOST_PORT%%:*}"
DB_PORT="${DB_HOST_PORT##*:}"

ABS_SQL_FILE="$(cd "$(dirname "${SQL_FILE_INPUT}")" && pwd)/$(basename "${SQL_FILE_INPUT}")"

MYSQL_PWD="${DB_PASS}" mysql \
  -h "${DB_HOST}" \
  -P "${DB_PORT}" \
  -u "${DB_USER}" \
  --default-character-set=utf8mb4 \
  --init-command="SET NAMES utf8mb4" \
  "${DB_NAME}" < "${ABS_SQL_FILE}"
