#!/bin/bash
# 光湖驱动引擎 v2.1 · 毛毛服务器一键部署
# 粘贴到服务器终端回车即可
set -e
echo "⚡ 光湖驱动引擎 v2.1 · 毛毛服务器 175.178.176.145"

echo "[1/5] 环境: $(lsb_release -ds 2>/dev/null||cat /etc/os-release|head -1), $(nproc)核, $(free -h|grep Mem|awk '{print $2}')"

echo "[2/5] 安装Node.js..."
if command -v node &>/dev/null; then echo "  $(node -v)"; else
  apt-get update -qq && apt-get install -y -qq curl
  curl -fsSL https://deb.nodesource.com/setup_22.x|bash -
  apt-get install -y nodejs && echo "  $(node -v)"
fi

echo "[3/5] 部署gatekeeper..."
mkdir -p /opt/guanghu /var/log/guanghu
# 尝试从仓库下载
curl -fsSL -o /opt/guanghu/gatekeeper.js \
  "https://guanghulab.com/code/bingshuo/guanghulab/raw/branch/main/_deploy/gatekeeper.js" 2>/dev/null \
|| curl -fsSL -o /opt/guanghu/gatekeeper.js \
  "https://gitee.com/lingdianyuanhe/zero-point-prokaryotic/raw/main/_deploy/gatekeeper.js" 2>/dev/null \
|| { echo "  下载失败，请手动上传gatekeeper.js到/opt/guanghu/"; exit 1; }
echo "  $(wc -c < /opt/guanghu/gatekeeper.js) bytes"

echo "[4/5] systemd服务..."
cat > /etc/systemd/system/guanghu-engine.service << 'SVC'
[Unit]
Description=光湖驱动引擎 v2.1
After=network.target
[Service]
Type=simple;User=root;WorkingDirectory=/opt/guanghu
ExecStartPre=/bin/bash -c 'fuser -k 3910/tcp 2>/dev/null;sleep 1;true'
ExecStart=/usr/bin/node /opt/guanghu/gatekeeper.js 3910
Restart=always;RestartSec=3
StandardOutput=append:/var/log/guanghu/engine.log
StandardError=append:/var/log/guanghu/engine.log
[Install]
WantedBy=multi-user.target
SVC
systemctl daemon-reload && systemctl enable guanghu-engine

echo "[5/5] 防火墙+启动..."
apt-get install -y -qq ufw 2>/dev/null; ufw --force enable 2>/dev/null
ufw allow 3910/tcp;ufw allow 80/tcp;ufw allow 22/tcp
systemctl restart guanghu-engine;sleep 2

echo "════════════════════════════════════════"
if systemctl is-active --quiet guanghu-engine; then
  S=$(cat /root/.gk/secret)
  echo "✅ 成功! 端口3910 密钥:$S"
  echo "curl -X POST http://175.178.176.145:3910/ping -H 'Authorization: Bearer $S'"
else
  echo "❌ 失败 journalctl -u guanghu-engine -n 30"
fi
echo "════════════════════════════════════════"
