#!/bin/bash

# Nginx 启动脚本 - 支持环境变量配置

set -e

# 默认环境变量
export NGINX_PORT=${NGINX_PORT:-80}
export SERVER_NAME=${SERVER_NAME:-localhost}
export API_PREFIX=${API_PREFIX:-/prod-api}
export BACKEND_HOST=${BACKEND_HOST:-qaup-app}
export BACKEND_PORT=${BACKEND_PORT:-8080}
export PROXY_CONNECT_TIMEOUT=${PROXY_CONNECT_TIMEOUT:-30s}
export PROXY_SEND_TIMEOUT=${PROXY_SEND_TIMEOUT:-60s}
export PROXY_READ_TIMEOUT=${PROXY_READ_TIMEOUT:-60s}
export MAX_UPLOAD_SIZE=${MAX_UPLOAD_SIZE:-20M}
export STATIC_CACHE_TIME=${STATIC_CACHE_TIME:-1y}

echo "启动 Nginx 服务..."
echo "配置参数:"
echo "  端口: $NGINX_PORT"
echo "  服务器名: $SERVER_NAME"
echo "  API 前缀: $API_PREFIX"
echo "  后端地址: $BACKEND_HOST:$BACKEND_PORT"

# 如果存在环境配置模板，则使用 envsubst 替换变量
if [ -f "/etc/nginx/conf.d/nginx-env.conf.template" ]; then
    echo "使用环境变量配置模板..."
    envsubst < /etc/nginx/conf.d/nginx-env.conf.template > /etc/nginx/conf.d/default.conf
    rm -f /etc/nginx/conf.d/nginx-env.conf.template
fi

# 测试 Nginx 配置
echo "测试 Nginx 配置..."
nginx -t

# 启动 Nginx
echo "启动 Nginx..."
exec nginx -g "daemon off;"