#!/bin/bash

# ==============================================================================
# 部署脚本 - Rust Backend
# ==============================================================================

# --- 1. 配置 ---
PROJECT_NAME="rust-backend"
REMOTE_USER="root"
REMOTE_HOST="1panel-server"
REMOTE_DIR="/root/rust/rust_backend"
SERVICE_NAME="rust-backend.service"

# --- 2. 脚本初始化 ---
set -euo pipefail

log_info() {
    echo -e "\033[32m[INFO]\033[0m $1"
}

log_error() {
    echo -e "\033[31m[ERROR]\033[0m $1" >&2
    exit 1
}

# --- 3. 检查依赖 ---
check_dependencies() {
    local deps=("cargo" "rsync" "ssh")
    for cmd in "${deps[@]}"; do
        if ! command -v "$cmd" &> /dev/null; then
            log_error "依赖命令 '$cmd' 未找到，请先安装。"
        fi
    done
    log_info "所有依赖项检查通过。"
}

# --- 4. 编译项目 ---
build_project() {
    log_info "开始编译项目 (release模式)..."
    if cargo build --release; then
        log_info "项目编译成功。"
    else
        log_error "项目编译失败！"
    fi
}

# --- 5. 上传二进制文件 ---
upload_binary() {
    local binary_path="./target/release/${PROJECT_NAME}"
    if [ ! -f "$binary_path" ]; then
        log_error "编译产物未找到: $binary_path"
    fi

    log_info "正在上传二进制文件到 ${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}..."
    rsync -avzP --progress "$binary_path" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_DIR}/"
    log_info "文件上传成功。"
}

# --- 6. 重启远程服务 ---
restart_remote_service() {
    log_info "正在重启远程服务 '${SERVICE_NAME}'..."
    if ssh "${REMOTE_USER}@${REMOTE_HOST}" "systemctl restart ${SERVICE_NAME}"; then
        log_info "远程服务重启成功。"
    else
        log_error "远程服务重启失败！请检查服务状态和日志。"
    fi
}

# --- 7. 主执行流程 ---
main() {
    log_info "========== 开始部署 =========="
    check_dependencies
    build_project
    upload_binary
    restart_remote_service
    log_info "========== 部署完成！ =========="
}

main
