start_all.sh 2.65 KB
#!/bin/bash

BASE_DIR=$(cd "$(dirname "$0")"; pwd)

# Load shared configuration
if [ -f "$BASE_DIR/.env.sh" ]; then
    source "$BASE_DIR/.env.sh"
else
    echo "Error: .env.sh not found in $BASE_DIR"
    exit 1
fi

# IP Filter Switch (Default to true for security)
export ENABLE_IP_FILTER="${ENABLE_IP_FILTER:-true}"

# Bypass proxy for local connections
export no_proxy="localhost,127.0.0.1,0.0.0.0,::1"
export NO_PROXY="localhost,127.0.0.1,0.0.0.0,::1"

FRONTEND_DIR="$BASE_DIR/z-image-generator"
BACKEND_DIR="$BASE_DIR"
CONFIG_JS_FILE="$BASE_DIR/public/config.js"
LOGS_DIR="$BASE_DIR/logs"

# Ensure logs directory exists
mkdir -p "$LOGS_DIR"
# Ensure frontend dist exists or create it
mkdir -p "$FRONTEND_DIR/dist"

echo "=================================================="
echo "Initializing Front-Backend Z-Image Services (PM2)"
echo "=================================================="

# 1. Generate Runtime Config (config.js)
echo "Generating runtime configuration in $CONFIG_JS_FILE..."
mkdir -p "$(dirname "$CONFIG_JS_FILE")"

cat > "$CONFIG_JS_FILE" <<EOF
window.APP_CONFIG = {
  Z_IMAGE_DIRECT_BASE_URL: "http://$PUBLIC_IP:$PUBLIC_ZIMAGE_PORT",
  TURBO_DIFFUSION_API_URL: "http://$PUBLIC_IP:$PUBLIC_TURBO_PORT",
  VIDEO_OSS_BASE_URL: "http://$PUBLIC_IP:$PUBLIC_OSS_PORT",
  API_BASE_URL: "http://$PUBLIC_IP:$PUBLIC_BACKEND_PORT",
  VIDEO_GENERATION_LIMIT: ${VIDEO_GENERATION_LIMIT:-1},
  LIKES_FOR_REWARD: ${LIKES_FOR_REWARD:-5}
};
EOF
# Copy config to frontend dist to ensure it is served
cp "$CONFIG_JS_FILE" "$FRONTEND_DIR/dist/config.js"

export TURBO_DIFFUSION_LOCAL_URL="http://127.0.0.1:$LOCAL_TURBO_PORT"
export VITE_API_BASE_URL="http://$PUBLIC_IP:$PUBLIC_BACKEND_PORT"
export WHITELIST_PATH="$BASE_DIR/backend/whitelist.txt"

echo "Configuration generated."

# 2. Check/Build Frontend
echo "Checking frontend build..."
if [ ! -d "$FRONTEND_DIR/dist" ]; then
    echo "Dist folder not found. Building frontend..."
    cd "$FRONTEND_DIR"
    npm run build
    cd "$BASE_DIR"
fi

# 3. Start PM2
echo "Starting services with PM2..."
cd "$BASE_DIR"
if command -v pm2 &> /dev/null; then
    # 显式指定配置文件,并使用 --update-env 确保环境变量同步
    pm2 start ecosystem.config.js --update-env
    pm2 save
    echo "Services started via PM2."
    pm2 list
else
    echo "Error: PM2 not found. Please install pm2 (npm install -g pm2) or use old start script."
    exit 1
fi

echo "=================================================="
echo "Frontend: http://$PUBLIC_IP:$PUBLIC_FRONTEND_PORT (Mapped from $LOCAL_FRONTEND_PORT)"
echo "Backend:  http://$PUBLIC_IP:$PUBLIC_BACKEND_PORT (Mapped from $LOCAL_BACKEND_PORT)"
echo "=================================================="