#!/bin/bash
# ============================================
# Nacos 启动脚本 — 根据环境变量生成 application.properties
# 环境变量: MYSQL-HOST MYSQL-PORT MYSQL-DB MYSQL-USER MYSQL-PWD
# ============================================
set -e

CONF_DIR="${NACOS_HOME:-/app}/conf"
mkdir -p "$CONF_DIR"

MYSQL_HOST="${MYSQL_HOST:-mysql}"
MYSQL_PORT="${MYSQL_PORT:-3306}"
MYSQL_DB="${MYSQL_DB:-nacos}"
MYSQL_USER="${MYSQL_USER:-root}"
MYSQL_PWD="${MYSQL_PWD:-root}"

echo ">>> Nacos 数据库配置:"
echo "    Host: ${MYSQL_HOST}:${MYSQL_PORT}"
echo "    DB:   ${MYSQL_DB}"
echo "    User: ${MYSQL_USER}"

cat > "$CONF_DIR/application.properties" << EOF
# Nacos 数据源配置（由 startup.sh 自动生成）
server.port=8848
spring.sql.init.platform=mysql
db.num=1
db.url.0=jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DB}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai
db.user.0=${MYSQL_USER}
db.password.0=${MYSQL_PWD}
EOF

echo ">>> 启动 Nacos..."
exec java ${JAVA_OPTS:-"-Xms512m -Xmx512m"} -jar /app/app.jar
