#!/bin/bash
# AI Interview 服务器部署脚本
# ============================================
# 在服务器上执行此脚本来快速部署
# 
# 使用方法:
#   chmod +x setup-server.sh
#   ./setup-server.sh
# ============================================

set -e

echo "=========================================="
echo "AI Interview 部署脚本"
echo "=========================================="

# 项目目录
PROJECT_DIR="/www/wwwroot/ai-interview"
DEPLOY_DIR="$PROJECT_DIR/deploy"

# 进入部署目录
cd $DEPLOY_DIR

# 1. 复制环境变量文件
if [ ! -f ".env" ]; then
    echo "[1/4] 创建 .env 文件..."
    cp env.production .env
    echo "✅ .env 文件已创建"
else
    echo "[1/4] .env 文件已存在，跳过"
fi

# 2. 创建上传目录
echo "[2/4] 创建上传目录..."
mkdir -p $DEPLOY_DIR/uploads
chmod 755 $DEPLOY_DIR/uploads
echo "✅ 上传目录已创建"

# 3. 停止旧容器
echo "[3/4] 停止旧容器..."
docker-compose down 2>/dev/null || true
echo "✅ 旧容器已停止"

# 4. 构建并启动新容器
echo "[4/4] 构建并启动容器..."
docker-compose up -d --build

# 等待服务启动
echo ""
echo "等待服务启动..."
sleep 5

# 检查容器状态
echo ""
echo "=========================================="
echo "容器状态:"
echo "=========================================="
docker-compose ps

# 检查服务健康
echo ""
echo "=========================================="
echo "健康检查:"
echo "=========================================="

# 检查后端
if curl -s http://127.0.0.1:8000/health > /dev/null 2>&1; then
    echo "✅ 后端服务正常 (http://127.0.0.1:8000)"
else
    echo "❌ 后端服务未响应"
    echo "查看后端日志: docker logs ai-interview-backend"
fi

# 检查前端
if curl -s http://127.0.0.1:3000 > /dev/null 2>&1; then
    echo "✅ 前端服务正常 (http://127.0.0.1:3000)"
else
    echo "❌ 前端服务未响应"
    echo "查看前端日志: docker logs ai-interview-frontend"
fi

echo ""
echo "=========================================="
echo "部署完成!"
echo "=========================================="
echo ""
echo "访问地址:"
echo "  - 用户端: http://interview.test.ai.ireborn.com.cn"
echo "  - 后台: http://interview.test.ai.ireborn.com.cn/admin"
echo "  - API: http://interview.test.ai.ireborn.com.cn/api/health"
echo ""
echo "常用命令:"
echo "  - 查看日志: docker-compose logs -f"
echo "  - 重启服务: docker-compose restart"
echo "  - 停止服务: docker-compose down"
echo ""
