#!/bin/bash

set -e

# =========================
# 可配置项（以后只改这里）
# =========================
# GitHub 代理前缀（留空表示直连 GitHub）
GITHUB_PROXY="https://github.govless.pp.ua/"

INSTALL_DIR="/opt/npc"
SERVICE_FILE="/etc/systemd/system/npc.service"

# =========================
# 用户输入
# =========================
read -p "请输入服务器地址 (格式: IP:端口): " SERVER_ADDR
read -p "请输入客户端验证密钥 (vkey): " VKEY

# =========================
# 检查并安装依赖
# =========================
install_pkg() {
    if command -v apt >/dev/null 2>&1; then
        apt update -y && apt install -y "$@"
    elif command -v yum >/dev/null 2>&1; then
        yum install -y "$@"
    elif command -v apk >/dev/null 2>&1; then
        apk add --no-cache "$@"
    else
        echo "❌ 不支持的包管理器"
        exit 1
    fi
}

command -v curl >/dev/null 2>&1 || { echo "安装 curl..."; install_pkg curl; }
command -v tar  >/dev/null 2>&1 || { echo "安装 tar...";  install_pkg tar; }

# =========================
# 获取系统架构
# =========================
ARCH=$(uname -m)
case "$ARCH" in
  x86_64) ARCH_NAME="linux_amd64_client" ;;
  aarch64 | arm64) ARCH_NAME="linux_arm64_client" ;;
  armv7l | armv6l) ARCH_NAME="linux_arm_client" ;;
  i386 | i686) ARCH_NAME="linux_386_client" ;;
  *) echo "❌ 不支持的架构: $ARCH" && exit 1 ;;
esac

# =========================
# 获取最新版本
# =========================
echo "🔍 正在获取最新版本..."
LATEST_VERSION=$(curl -s \
  --connect-timeout 10 \
  --retry 5 \
  --retry-delay 3 \
  "${GITHUB_PROXY}https://api.github.com/repos/yisier/nps/releases/latest" \
  | grep tag_name | cut -d '"' -f 4)

if [ -z "$LATEST_VERSION" ]; then
    echo "❌ 获取版本失败"
    exit 1
fi

echo "✅ 最新版本: $LATEST_VERSION"

# =========================
# 下载并安装 npc
# =========================
DOWNLOAD_URL="${GITHUB_PROXY}https://github.com/yisier/nps/releases/download/${LATEST_VERSION}/${ARCH_NAME}.tar.gz"
TMP_DIR=$(mktemp -d)

echo "⬇️  下载中: $DOWNLOAD_URL"
curl -L \
  --connect-timeout 10 \
  --retry 5 \
  --retry-delay 3 \
  -o "$TMP_DIR/npc.tar.gz" "$DOWNLOAD_URL"

mkdir -p "$INSTALL_DIR"
tar -xzf "$TMP_DIR/npc.tar.gz" -C "$TMP_DIR"
mv "$TMP_DIR/npc" "$INSTALL_DIR/npc"
chmod +x "$INSTALL_DIR/npc"

# =========================
# 创建 systemd 服务
# =========================
cat <<EOF > "$SERVICE_FILE"
[Unit]
Description=NPC Client
After=network.target

[Service]
Type=simple
ExecStart=${INSTALL_DIR}/npc -server=${SERVER_ADDR} -vkey=${VKEY}
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

# =========================
# 启动服务
# =========================
systemctl daemon-reexec
systemctl daemon-reload
systemctl enable npc.service
systemctl restart npc.service

echo "✅ npc 已安装并启动"
systemctl status npc.service --no-pager
