#!/bin/bash
# 进销存管理系统 - Linux 服务端编译脚本（免费版）

echo "============================================"
echo "  进销存管理系统 - Linux 服务端编译"
echo "============================================"
echo ""

# ── 0. 配置国内镜像加速 ──
mkdir -p "$HOME/.cargo"
cat > "$HOME/.cargo/config.toml" << 'EOF'
[source.crates-io]
replace-with = 'ustc'

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"

[net]
git-fetch-with-cli = true
EOF
echo "[0/3] 已配置中科大镜像加速"
echo ""

# ── 1. 检查编译工具链 ──
if ! command -v gcc &> /dev/null; then
    echo "[1/3] 安装编译工具链..."
    if command -v apt &> /dev/null; then
        apt update -qq && apt install build-essential -y -qq
    elif command -v yum &> /dev/null; then
        yum groupinstall "Development Tools" -y -q
    elif command -v dnf &> /dev/null; then
        dnf groupinstall "Development Tools" -y -q
    fi
    echo ""
fi

# ── 2. 检查 Rust ──
if ! command -v cargo &> /dev/null; then
    echo "[2/3] 安装 Rust..."
    export RUSTUP_DIST_SERVER="https://mirrors.ustc.edu.cn/rust-static"
    export RUSTUP_UPDATE_ROOT="https://mirrors.ustc.edu.cn/rust-static/rustup"
    
    if curl --proto '=https' --tlsv1.2 -sSf --connect-timeout 10 https://sh.rustup.rs -o /tmp/rustup-init.sh; then
        sh /tmp/rustup-init.sh -y
        rm -f /tmp/rustup-init.sh
    else
        echo ""
        echo "  网络不通，尝试通过包管理器安装..."
        if command -v apt &> /dev/null; then
            apt install -y cargo 2>/dev/null || true
        elif command -v yum &> /dev/null; then
            yum install -y cargo 2>/dev/null || true
        elif command -v dnf &> /dev/null; then
            dnf install -y cargo 2>/dev/null || true
        fi
    fi
    
    if ! command -v cargo &> /dev/null; then
        echo ""
        echo "  ========================================="
        echo "  Rust 安装失败，请手动安装："
        echo "  curl https://sh.rustup.rs -sSf | sh"
        echo "  如网络不通，先执行："
        echo "  export RUSTUP_DIST_SERVER=https://mirrors.ustc.edu.cn/rust-static"
        echo "  export RUSTUP_UPDATE_ROOT=https://mirrors.ustc.edu.cn/rust-static/rustup"
        echo "  ========================================="
        exit 1
    fi
    source "$HOME/.cargo/env"
    echo ""
fi

echo "工具链: gcc $(gcc --version 2>/dev/null | head -1 | awk '{print $NF}'), $(cargo --version)"
echo ""

# ── 3. 编译 ──
echo "[3/3] 编译中（首次约需 5-10 分钟）..."
cd "$(dirname "$0")/server"
cargo build --release

if [ $? -eq 0 ]; then
    echo ""
    echo "============================================"
    echo "  ✅ 编译完成！"
    echo "============================================"
    echo "  前台运行："
    echo "  ./server/target/release/inventory-server"
    echo ""
    echo "  后台运行："
    echo "  nohup ./server/target/release/inventory-server > server.log 2>&1 &"
    echo "============================================"
else
    echo ""
    echo "❌ 编译失败，请检查错误信息"
    exit 1
fi