#!/bin/bash

set -e

DOCKER_DIR="../../docker"
SQL_DIR="../../sql"

echo "=========================================="
echo "部署 MySQL"
echo "=========================================="

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

    echo "删除旧的 MySQL StatefulSet..."
    kubectl delete statefulset mysql -n ruoyi --ignore-not-found=true

    echo "删除旧的 MySQL Service..."
    kubectl delete service ruoyi-mysql -n ruoyi --ignore-not-found=true

    echo "删除旧的 PVC（数据将被清空）..."
    kubectl delete pvc -l app=mysql -n ruoyi --ignore-not-found=true

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

    echo "✓ 旧数据清理完成"
fi

echo ""

# 步骤 1: 复制 SQL 文件
echo "步骤 1: 复制 SQL 文件到 docker/mysql/db..."
cp "$SQL_DIR/ry_20250523.sql" "$DOCKER_DIR/mysql/db/"
cp "$SQL_DIR/ry_config_20250902.sql" "$DOCKER_DIR/mysql/db/"
echo "✓ SQL 文件复制完成"

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

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

    # 先导出镜像到临时文件
    TEMP_IMAGE="/tmp/mysql-runtime-$$.tar"
    echo "导出镜像到临时文件..."
    docker save -o "$TEMP_IMAGE" mysql-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 分钟）"
            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

# 步骤 3: 部署到 K8s
echo ""
echo "步骤 3: 部署到 Kubernetes..."
cd -
kubectl apply -f service.yaml
kubectl apply -f statefulset.yaml

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

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

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

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

echo ""

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

echo ""

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

echo ""
echo "=========================================="
echo "✓ MySQL 部署完成！"
echo "=========================================="
echo ""
echo "连接信息："
echo "  Service: ruoyi-mysql.ruoyi.svc.cluster.local"
echo "  端口: 3306"
echo "  用户: root"
echo "  密码: password"
echo "  数据库: ry-cloud"
echo ""
exit 0
