#!/bin/bash

set -e

# 保存脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DOCKER_DIR="$SCRIPT_DIR/../../docker"

echo "=========================================="
echo "部署 File"
echo "=========================================="

# 检查是否需要清理旧部署
echo ""
echo "检查现有 File 部署..."
if kubectl get deployment file -n ruoyi &> /dev/null; then
    echo "⚠️  检测到已存在的 File 部署，自动清理..."

    echo "删除旧的 File Deployment..."
    kubectl delete deployment file -n ruoyi --ignore-not-found=true

    echo "删除旧的 File Service..."
    kubectl delete service ruoyi-modules-file -n ruoyi --ignore-not-found=true

    echo "等待资源清理完成..."
    sleep 5

    echo "✓ 旧部署清理完成"
fi

echo ""
# 步骤 1: 打包 File
echo "步骤 1: 打包 File jar..."
cd "$SCRIPT_DIR/../../bin"
sh package.sh ruoyi-modules-file
if [ $? -eq 0 ]; then
    echo "✓ File 打包完成"
else
    echo "✗ File 打包失败"
    exit 1
fi

# 步骤 2: 复制 jar 文件
echo ""
echo "步骤 2: 复制 File jar 文件..."
cp "$SCRIPT_DIR/../../ruoyi-modules/ruoyi-file/target/ruoyi-modules-file.jar" "$DOCKER_DIR/ruoyi/modules/file/jar/"
echo "✓ jar 文件复制完成"

# 步骤 3: 构建 File 镜像
echo ""
echo "步骤 3: 构建 File 镜像..."
cd "$DOCKER_DIR"
docker-compose build --no-cache ruoyi-modules-file
if [ $? -eq 0 ]; then
    echo "✓ File 镜像构建完成"
else
    echo "✗ File 镜像构建失败"
    exit 1
fi

# 步骤 3.5: 检测环境并导入镜像（仅 Minikube 需要）
echo ""
if command -v minikube &> /dev/null && minikube status &> /dev/null; then
    echo "检测到 Minikube 环境，导入镜像（可能需要 1-2 分钟）..."

    # 先导出镜像到临时文件
    TEMP_IMAGE="/tmp/ruoyi-modules-file-runtime-$$.tar"
    echo "导出镜像到临时文件..."
    docker save -o "$TEMP_IMAGE" ruoyi-modules-file-runtime

    # 导入到 Minikube
    echo "导入镜像到 Minikube..."
    minikube image load "$TEMP_IMAGE" &
    PID=$!

    # 显示进度，最多等待 5 分钟
    COUNT=0
    MAX_COUNT=150
    while kill -0 $PID 2>/dev/null; do
        echo -n "."
        sleep 2
        COUNT=$((COUNT + 1))
        if [ $COUNT -ge $MAX_COUNT ]; then
            kill $PID 2>/dev/null
            echo ""
            echo "✗ 镜像导入超时（超过 5 分钟）"
            rm -f "$TEMP_IMAGE"
            exit 1
        fi
    done
    wait $PID
    EXIT_CODE=$?

    echo ""
    if [ $EXIT_CODE -eq 0 ]; then
        echo "✓ 镜像导入到 Minikube 完成"
    else
        echo "✗ 镜像导入失败"
        rm -f "$TEMP_IMAGE"
        exit 1
    fi

    # 清理临时文件
    rm -f "$TEMP_IMAGE"
else
    echo "检测到 k3s/k8s 环境，跳过镜像导入（使用本地 Docker 镜像）"
fi

# 步骤 4: 部署到 K8s
echo ""
echo "步骤 4: 部署到 Kubernetes..."
cd "$SCRIPT_DIR"
kubectl apply -f pvc.yaml
kubectl apply -f service.yaml
kubectl apply -f deployment.yaml

# 步骤 5: 等待 Pod 启动
echo ""
echo "步骤 5: 等待 File Pod 启动..."
kubectl wait --for=condition=ready pod -l app=file -n ruoyi --timeout=300s

if [ $? -ne 0 ]; then
    echo "✗ File Pod 启动超时"
    exit 1
fi

# 检查部署状态
echo ""
echo "=========================================="
echo "检查部署结果"
echo "=========================================="

# 检查 Pod 状态
echo "检查 File Pod 状态..."
POD_STATUS=$(kubectl get pods -n ruoyi -l app=file -o jsonpath='{.items[0].status.phase}')
if [ "$POD_STATUS" == "Running" ]; then
    echo "✓ File Pod 运行正常"
    kubectl get pods -n ruoyi -l app=file
else
    echo "✗ File Pod 状态异常: $POD_STATUS"
    kubectl get pods -n ruoyi -l app=file
    exit 1
fi

echo ""
# 检查 Service 状态
echo "检查 File Service 状态..."
if kubectl get svc ruoyi-modules-file -n ruoyi &> /dev/null; then
    echo "✓ File Service 创建成功"
    kubectl get svc -n ruoyi ruoyi-modules-file
else
    echo "✗ File Service 创建失败"
    exit 1
fi

echo ""
# 检查 PVC 状态
echo "检查 File PVC 状态..."
PVC_STATUS=$(kubectl get pvc -n ruoyi file-upload-pvc -o jsonpath='{.status.phase}')
if [ "$PVC_STATUS" == "Bound" ]; then
    echo "✓ File PVC 绑定成功"
    kubectl get pvc -n ruoyi file-upload-pvc
else
    echo "✗ File PVC 状态异常: $PVC_STATUS"
    kubectl get pvc -n ruoyi file-upload-pvc
    exit 1
fi

echo ""
echo "=========================================="
echo "✓ File 部署完成！"
echo "=========================================="
echo ""
echo "访问信息："
echo "  Service: ruoyi-modules-file.ruoyi.svc.cluster.local"
echo "  端口: 9300"
echo "  上传路径: /var/lib/uploadPath"
echo ""
exit 0
