#!/bin/bash
# 为所有用户生成配置文件

echo "为所有用户生成配置文件..."

# 用户列表: username id
users=(
  "zhugeliang 1"
  "pangtong 2"
  "simayi 3"
  "zhangfei 4"
  "guanyu 5"
  "zhaoyun 6"
  "jiangwei 7"
)

BASE_DIR="/Users/chufeng/.openclaw/sanguo_projects/sanguo_vnpy"
TEMPLATE_DIR="/Users/chufeng/.openclaw/sanguo_projects/sanguo_vnpy/jiangwei-platform/deploy/nas/templates"
CONFIG_DIR="/Users/chufeng/.openclaw/sanguo_projects/sanguo_vnpy/config"

mkdir -p "$CONFIG_DIR"/{systemd,nginx}

for entry in "${users[@]}"; do
  read username id <<< "$entry"
  
  RPC_REQUEST_PORT=$((2000 + id * 10))
  RPC_SUBSCRIBE_PORT=$((RPC_REQUEST_PORT + 1))
  WEB_PORT=$((8000 + id))
  NGINX_PATH="/$username/"
  
  echo "----------------------------------------"
  echo "用户: $username, ID: $id"
  echo "  RPC请求: $RPC_REQUEST_PORT"
  echo "  RPC订阅: $RPC_SUBSCRIBE_PORT"
  echo "  Web端口: $WEB_PORT"
  
  # 生成启动脚本
  sed \
    -e "s/{{username}}/$username/g" \
    -e "s/{{rpc_request_port}}/$RPC_REQUEST_PORT/g" \
    -e "s/{{rpc_subscribe_port}}/$RPC_SUBSCRIBE_PORT/g" \
    "$TEMPLATE_DIR/start_trade.py.template" > "$BASE_DIR/users/$username/start_trade.py"
  
  sed \
    -e "s/{{username}}/$username/g" \
    -e "s/{{rpc_request_port}}/$RPC_REQUEST_PORT/g" \
    -e "s/{{rpc_subscribe_port}}/$RPC_SUBSCRIBE_PORT/g" \
    -e "s/{{web_port}}/$WEB_PORT/g" \
    "$TEMPLATE_DIR/start_web.py.template" > "$BASE_DIR/users/$username/start_web.py"
  
  chmod +x "$BASE_DIR/users/$username/start_trade.py" "$BASE_DIR/users/$username/start_web.py"
  
  # 生成systemd
  sed \
    -e "s/{{username}}/$username/g" \
    -e "s|{{base_dir}}|$BASE_DIR|g" \
    "$TEMPLATE_DIR/systemd/trade.service.template" > "$CONFIG_DIR/systemd/sanguo-trade-$username.service"
  
  sed \
    -e "s/{{username}}/$username/g" \
    -e "s|{{base_dir}}|$BASE_DIR|g" \
    "$TEMPLATE_DIR/systemd/web.service.template" > "$CONFIG_DIR/systemd/sanguo-web-$username.service"
  
  # 生成nginx - 使用!作为分隔符避免和路径斜杠冲突
  sed \
    -e "s!{{username}}!$username!g" \
    -e "s!{{nginx_path}}!$NGINX_PATH!g" \
    -e "s!{{web_port}}!$WEB_PORT!g" \
    "$TEMPLATE_DIR/nginx/location.conf.template" > "$CONFIG_DIR/nginx/$username.conf"
  
  echo "  配置生成完成"
done

echo "----------------------------------------"
echo "所有用户配置生成完成!"
echo ""
echo "输出目录:"
echo "  启动脚本: $BASE_DIR/users/<username>/"
echo "  systemd: $CONFIG_DIR/systemd/"
echo "  nginx: $CONFIG_DIR/nginx/"
