#!/usr/bin/env bash
set -euo pipefail
umask 077
[[ $(id -u) == 0 ]] || { echo '请使用 root 安装'; exit 1; }
command -v systemctl >/dev/null
command -v curl >/dev/null
[[ $(uname -m) == x86_64 ]] || { echo '当前下载为 Linux amd64'; exit 1; }
read -r -p '控制台 HTTPS 地址 [https://yxdun.cdn8.com]: ' console_url
[[ -n $console_url ]] || console_url=https://yxdun.cdn8.com
read -r -p '控制面 HTTPS 地址 [https://yxdun.cdn8.com/control]: ' control_url
[[ -n $control_url ]] || control_url=https://yxdun.cdn8.com/control
read -r -p '网关 ID: ' gateway_id
read -r -s -p '一次性网关令牌: ' gateway_token
echo
read -r -p '私有隧道 CA 文件路径（公开 CA 留空）: ' ca_path
[[ $console_url =~ ^https://[a-zA-Z0-9.-]+(:[0-9]+)?(/[a-zA-Z0-9/_-]*)?$ && $control_url =~ ^https://[a-zA-Z0-9.-]+(:[0-9]+)?(/[a-zA-Z0-9/_-]*)?$ ]] || { echo '生产安装要求有效 HTTPS 地址'; exit 1; }
[[ $gateway_id =~ ^gw_[a-f0-9]{16}$ && $gateway_token =~ ^[a-f0-9]{64}$ ]] || { echo '网关 ID 或令牌格式错误'; exit 1; }
install_dir=/opt/gameshield-gateway
[[ ! -L $install_dir && ! -L /etc/gameshield ]] || { echo '安装路径不允许符号链接'; exit 1; }
install -d -m 755 "$install_dir" /etc/gameshield
binary_tmp=$(mktemp "$install_dir/.gateway.XXXXXX")
trap 'rm -f -- "$binary_tmp"' EXIT
curl --fail --silent --show-error --proto '=https' --tlsv1.2 "$console_url/install/gateway-agent" -o "$binary_tmp"
chmod 755 "$binary_tmp"
mv -f -- "$binary_tmp" "$install_dir/gateway-agent"
env_tmp=$(mktemp /etc/gameshield/.gateway-env.XXXXXX)
printf 'GS_CONTROL_URL=%s
GS_GATEWAY_ID=%s
GS_GATEWAY_TOKEN=%s
' "$control_url" "$gateway_id" "$gateway_token" > "$env_tmp"
if [[ -n $ca_path ]]; then
 [[ -f $ca_path && ! -L $ca_path ]] || { echo 'CA 文件无效'; exit 1; }
 install -m 644 "$ca_path" "$install_dir/relay-ca.pem"
 printf 'GS_TUNNEL_CA_FILE=%s
' "$install_dir/relay-ca.pem" >> "$env_tmp"
fi
chmod 600 "$env_tmp"
mv -f -- "$env_tmp" /etc/gameshield/gateway.env
unset gateway_token
if ! id gameshield-gateway >/dev/null 2>&1; then useradd --system --no-create-home --shell /usr/sbin/nologin gameshield-gateway; fi
cat > /etc/systemd/system/gs-gateway.service <<'UNIT'
[Unit]
Description=GameShield Outbound Origin Gateway
After=network-online.target
Wants=network-online.target
[Service]
User=gameshield-gateway
Group=gameshield-gateway
EnvironmentFile=/etc/gameshield/gateway.env
ExecStart=/opt/gameshield-gateway/gateway-agent
Restart=on-failure
RestartSec=3
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
LimitNOFILE=65536
[Install]
WantedBy=multi-user.target
UNIT
systemctl daemon-reload
systemctl enable gs-gateway
systemctl restart gs-gateway
sleep 2
systemctl is-active --quiet gs-gateway || { echo '网关启动失败，请查看 journalctl -u gs-gateway'; exit 1; }
echo '网关已启动；请在控制台确认真实隧道连接及规则状态。'
