#!/bin/bash
# MeshRay Linux 一键安装脚本

set -e

MESHRAY_VERSION="v2.0.0"
INSTALL_DIR="/opt/meshray"
SERVICE_NAME="meshray"

echo "🚀 MeshRay 安装脚本 v${MESHRAY_VERSION}"
echo "======================================"

# 检测系统架构
ARCH=$(uname -m)
case $ARCH in
    x86_64) ARCH="amd64" ;;
    aarch64) ARCH="arm64" ;;
    *) echo "❌ 不支持的架构：$ARCH"; exit 1 ;;
esac

echo "✅ 检测到系统架构：$ARCH"

# 检测 WireGuard 内核支持
if [ -d "/sys/module/wireguard" ]; then
    echo "✅ WireGuard 内核模块已加载"
    WG_MODE="kernel"
else
    echo "⚠️  WireGuard 内核模块未加载，将使用 wireguard-go 用户态"
    WG_MODE="userspace"
fi

# 创建安装目录
sudo mkdir -p $INSTALL_DIR
sudo mkdir -p /opt/meshray/data
sudo mkdir -p /opt/meshray/logs
sudo mkdir -p /opt/meshray/backups

# 下载 MeshRay（需要从 GitHub Releases 下载）
echo "📦 正在下载 MeshRay ${MESHRAY_VERSION}..."
# TODO: 替换为真实的下载链接
# wget -q https://git.zkcoi.com/zkcoi/meshray/releases/download/${MESHRAY_VERSION}/meshray-linux-${ARCH}.tar.gz
# tar -xzf meshray-linux-${ARCH}.tar.gz
# sudo mv meshray $INSTALL_DIR/

# 复制配置文件
if [ ! -f "$INSTALL_DIR/config.yaml" ]; then
    echo "📝 创建配置文件..."
    sudo cp configs/config.example.yaml $INSTALL_DIR/config.yaml
fi

# 安装 systemd 服务
echo "🔧 安装 systemd 服务..."
sudo cp deploy/systemd/meshray.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable $SERVICE_NAME

# 设置权限
echo "🔐 设置文件权限..."
sudo chown -R root:root $INSTALL_DIR
sudo chmod +x $INSTALL_DIR/meshray

echo ""
echo "✅ MeshRay 安装完成！"
echo ""
echo "启动服务：sudo systemctl start $SERVICE_NAME"
echo "查看状态：sudo systemctl status $SERVICE_NAME"
echo "查看日志：sudo journalctl -u $SERVICE_NAME -f"
echo ""
echo "Web UI: http://localhost:9531"
echo "默认端口可在 $INSTALL_DIR/config.yaml 中修改"
