#!/bin/bash

# 面试管理系统 - 快速部署脚本
# 使用方法: ./deploy.sh

set -e  # 遇到错误立即退出

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未安装，请先安装"
        exit 1
    fi
}

# 检查环境
print_info "检查环境..."
check_command node
check_command npm
check_command nginx

# 获取 Node.js 版本
NODE_VERSION=$(node -v)
print_info "Node.js 版本: $NODE_VERSION"

# 检查 Node.js 版本
if [[ $(echo $NODE_VERSION | cut -d'.' -f1 | sed 's/v//') -lt 16 ]]; then
    print_error "Node.js 版本需要 >= 16.0.0"
    exit 1
fi

# 获取当前目录
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$( cd "$SCRIPT_DIR/.." && pwd )"

print_info "项目目录: $PROJECT_DIR"

# 询问是否继续
read -p "是否继续部署? (y/n): " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    print_info "部署已取消"
    exit 0
fi

# 进入项目目录
cd "$PROJECT_DIR"

# 备份现有构建
if [ -d "dist" ]; then
    print_info "备份现有构建..."
    if [ -d "dist.backup" ]; then
        rm -rf dist.backup
    fi
    cp -r dist dist.backup
    print_info "备份完成"
fi

# 安装依赖
print_info "安装依赖..."
npm ci

# 构建项目
print_info "构建项目..."
npm run build

# 检查构建结果
if [ ! -d "dist" ] || [ -z "$(ls -A dist)" ]; then
    print_error "构建失败，dist 目录为空"
    exit 1
fi

print_info "构建完成"

# 询问是否部署到服务器
read -p "是否部署到服务器? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    # 部署路径
    DEPLOY_PATH="/var/www/interview_web"
    
    # 检查部署路径
    if [ ! -d "$DEPLOY_PATH" ]; then
        print_warn "部署路径不存在，创建中..."
        sudo mkdir -p "$DEPLOY_PATH"
        sudo chown -R $USER:www-data "$DEPLOY_PATH"
    fi
    
    # 备份服务器文件
    if [ -d "$DEPLOY_PATH" ] && [ "$(ls -A $DEPLOY_PATH)" ]; then
        print_info "备份服务器文件..."
        sudo cp -r "$DEPLOY_PATH" "${DEPLOY_PATH}.backup.$(date +%Y%m%d_%H%M%S)"
    fi
    
    # 复制文件
    print_info "复制文件到 $DEPLOY_PATH ..."
    sudo rm -rf "$DEPLOY_PATH"/*
    sudo cp -r dist/* "$DEPLOY_PATH"/
    sudo chown -R www-data:www-data "$DEPLOY_PATH"
    
    print_info "文件复制完成"
    
    # 重载 Nginx
    print_info "重载 Nginx..."
    sudo nginx -t && sudo systemctl reload nginx
    
    print_info "部署完成！"
    print_info "访问地址: http://yourdomain.com"
else
    print_info "跳过服务器部署"
fi

# 显示构建信息
print_info "构建信息:"
echo "  构建目录: dist/"
echo "  构建时间: $(date)"
echo "  Node.js 版本: $NODE_VERSION"
echo "  项目版本: $(cat package.json | grep '"version"' | cut -d'"' -f4)"

print_info "部署脚本执行完成！"

