#!/bin/bash

set -e

# ===== 用户配置部分 =====
STEAM_USER="nangonglingzhi"
STEAM_PASS="Ng011245"
SERVER_NAME="菜鸡服务器"
MAX_PLAYERS=8
MAP="Oilfield"
SCENARIO="Scenario_Oilfield_Checkpoint_Security"
SERVER_PORT=7777
QUERY_PORT=27015
RCON_PORT=27015

# ===== 安装依赖 =====
echo "📦 安装依赖..."
sudo dpkg --add-architecture i386
sudo apt update
sudo apt install -y lib32gcc-s1 curl unzip tar ca-certificates libstdc++6 libcurl4-gnutls-dev

# ===== 安装 SteamCMD =====
mkdir -p ~/steamcmd && cd ~/steamcmd
if [ ! -f "./steamcmd.sh" ]; then
    echo "⬇️ 下载 SteamCMD..."
    curl -sSL https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz | tar -xzv
fi

# ===== 下载服务器文件 =====
INSTALL_DIR=~/insurgency_server
mkdir -p "$INSTALL_DIR"
echo "🎮 下载 Insurgency Sandstorm 服务器文件..."
./steamcmd.sh +login "$STEAM_USER" "$STEAM_PASS" \
  +force_install_dir "$INSTALL_DIR" \
  +app_update 581330 validate \
  +quit

# ===== 生成配置文件 =====
CONFIG_DIR="$INSTALL_DIR/Insurgency/Saved/Config/LinuxServer"
mkdir -p "$CONFIG_DIR"

# -- ServerSettings.ini --
cat > "$CONFIG_DIR/ServerSettings.ini" <<EOF
[/Script/Insurgency.INSGameMode]
bAllowXP=True
bAllowStats=True

[/Script/Insurgency.INSGameSession]
ServerName=$SERVER_NAME
EOF

# -- Game.ini --
cat > "$CONFIG_DIR/Game.ini" <<EOF
[/Script/Insurgency.INSCheckpointGameMode]
AIDifficulty=1.0
MinimumEnemies=10
MaximumEnemies=20
FriendlyBotQuota=2
bBots=True
EOF

# ===== 启动脚本 =====
START_SCRIPT="$INSTALL_DIR/start_server.sh"
cat > "$START_SCRIPT" <<EOF
#!/bin/bash
cd "$INSTALL_DIR"
./Insurgency/Binaries/Linux/InsurgencyServer-Linux-Shipping \\
  $MAP?Scenario=$SCENARIO?MaxPlayers=$MAX_PLAYERS \\
  -Port=$SERVER_PORT -QueryPort=$QUERY_PORT -log
EOF

chmod +x "$START_SCRIPT"

echo "✅ 安装完成！"
echo "🟢 启动服务器：$START_SCRIPT"
