#!/bin/bash

# 确保在脚本所在目录执行
cd "$(dirname "$0")"
SCRIPT_DIR="$(pwd)"
echo "当前工作目录: $SCRIPT_DIR"

# 获取项目根目录
ROOT_DIR="$(cd ../.. && pwd)"
echo "项目根目录: $ROOT_DIR"

# 加载环境变量
source "$ROOT_DIR/environment.sh"
echo "已加载环境变量"

# 执行变量替换脚本
echo "开始替换环境变量..."
bash "$SCRIPT_DIR/replace_vars.sh"

# 检查替换是否成功
if [ ! -f "$SCRIPT_DIR/temp/application.yml" ]; then
    echo "错误: 替换后的配置文件不存在: $SCRIPT_DIR/temp/application.yml"
    exit 1
fi

echo "配置文件替换成功，准备启动Gateway容器..."

# 先停止和删除现有容器
if docker ps -a | grep -q ${GATEWAY_NAME}; then
    echo "停止并删除已存在的 ${GATEWAY_NAME} 容器..."
    docker stop ${GATEWAY_NAME} >/dev/null 2>&1
    docker rm ${GATEWAY_NAME} >/dev/null 2>&1
fi

# 启动Gateway容器
echo "正在启动 ${GATEWAY_NAME} 容器..."
docker run --pull always -d \
    --name ${GATEWAY_NAME} \
    --network ${NETWORK} \
    -p 7021:7011 \
    --add-host ${OIDC_SERVER_DOMAIN}:host-gateway \
    --env TZ=Asia/Shanghai \
    --env SPRING_CONFIG_LOCATION=file:/data/java/tuoheng/application.yml \
    --mount type=bind,source=/etc/localtime,target=/etc/localtime,readonly \
    --mount type=bind,source="$SCRIPT_DIR/temp/application.yml",target=/data/java/tuoheng/application.yml,readonly \
    --memory ${GATEWAY_MEMORY} \
    --restart unless-stopped \
    ${GATEWAY_IMAGE}

# 检查启动结果
if [ $? -eq 0 ]; then
    echo "Gateway服务已成功启动"
    docker ps | grep ${GATEWAY_NAME}
else
    echo "Gateway服务启动失败，请检查日志"
    docker logs ${GATEWAY_NAME}
fi 