#!/usr/bin/env bash
# =========================================================
# 一键启动 + 开机自启 KMS 服务器 (vlmcsd)
# 默认端口: 1688
# 安装目录: /usr/local/kms
# 日志位置: /var/log/vlmcsd.log
# =========================================================

set -e

KMS_DIR="/usr/local/kms"
KMS_BIN="$KMS_DIR/vlmcsd"
KMS_LOG="/var/log/vlmcsd.log"
SERVICE_FILE="/etc/systemd/system/vlmcsd.service"

# 检查程序是否存在
if [ ! -f "$KMS_BIN" ]; then
    echo "❌ 未找到 $KMS_BIN"
    echo "请确认 vlmcsd 已安装在 /usr/local/kms"
    exit 1
fi

chmod +x "$KMS_BIN"

# 创建 systemd 服务
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=KMS Server (vlmcsd)
After=network.target

[Service]
Type=simple
ExecStart=${KMS_BIN} -l ${KMS_LOG} -D
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable vlmcsd
systemctl restart vlmcsd

sleep 1
if pgrep -x "vlmcsd" >/dev/null; then
    echo "✅ KMS 已启动成功"
    echo "📜 日志文件: $KMS_LOG"
    echo "🌐 默认监听端口: 1688"
else
    echo "⚠️ 启动失败，请检查日志: $KMS_LOG"
fi
