#!/bin/bash
# EasyRemote Server Linux 构建脚本
# 在 Linux 服务器上运行此脚本来构建服务端

set -e

echo "====================================="
echo "  EasyRemote Server Linux Build"
echo "====================================="

# 检查 Rust 是否安装
if ! command -v cargo &> /dev/null; then
    echo "Rust 未安装，正在安装..."
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
    source $HOME/.cargo/env
fi

echo "Rust 版本: $(rustc --version)"
echo "Cargo 版本: $(cargo --version)"

# 构建服务端
echo ""
echo "正在构建服务端..."
cargo build --release --package easyremote-server

# 创建发布目录
RELEASE_DIR="./release/linux"
mkdir -p "$RELEASE_DIR"

# 复制文件
cp target/release/easyremote-server "$RELEASE_DIR/"
cp -r crates/server/static "$RELEASE_DIR/"

# 创建启动脚本
cat > "$RELEASE_DIR/start.sh" << 'EOF'
#!/bin/bash
cd "$(dirname "$0")"
./easyremote-server
EOF
chmod +x "$RELEASE_DIR/start.sh"

# 创建 systemd 服务文件
cat > "$RELEASE_DIR/easyremote.service" << 'EOF'
[Unit]
Description=EasyRemote Server
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/opt/easyremote
ExecStart=/opt/easyremote/easyremote-server
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

echo ""
echo "====================================="
echo "  构建完成！"
echo "====================================="
echo ""
echo "发布文件位于: $RELEASE_DIR/"
echo ""
echo "文件列表:"
ls -la "$RELEASE_DIR/"
echo ""
echo "部署步骤:"
echo "1. 复制 release/linux/ 目录到服务器 /opt/easyremote/"
echo "2. 复制 easyremote.service 到 /etc/systemd/system/"
echo "3. 运行: systemctl daemon-reload"
echo "4. 运行: systemctl enable easyremote"
echo "5. 运行: systemctl start easyremote"
echo ""
echo "或者直接运行: ./start.sh"
