#!/bin/bash

# CMII Live Services (Merged) Helm 部署脚本
# 特性: WVP + ZLM + ZLM-OSS 合并部署,使用 HostNetwork 模式访问
# live-op | live-proxy | live-helper node port 模式访问
# ============================说明=====================================
# 如果你不需要使用此脚本文件，直接使用 helm install/upgrade ${release_name} . -n ${namespace_name} 启动
# 或者 kubectl apply -f templates/** 创建
# =====================================================================

set -e

# 配置变量 (***配置namespace & releaseName)
RELEASE_NAME="helm-live"
NAMESPACE="uavcloud-live-test"
CHART_PATH="$(cd "$(dirname "$0")" && pwd)"
VALUES_FILE="${CHART_PATH}/values.yaml"

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

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

echo_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查前置条件
check_prerequisites() {
    echo_step "检查前置条件..."

    # 检查 kubectl
    if ! command -v kubectl &> /dev/null; then
        echo_error "kubectl 未安装,请先安装 kubectl"
        exit 1
    fi

    # 检查 helm
    if ! command -v helm &> /dev/null; then
        echo_error "helm 未安装,请先安装 helm 3.x"
        exit 1
    fi

    # 检查 Kubernetes 连接
    if ! kubectl cluster-info &> /dev/null; then
        echo_error "无法连接到 Kubernetes 集群,请检查 kubeconfig 配置"
        exit 1
    fi

    echo_info "前置条件检查通过"
}

# 创建命名空间
create_namespace() {
    echo_step "创建命名空间: ${NAMESPACE}"
    kubectl create namespace ${NAMESPACE} --dry-run=client -o yaml | kubectl apply -f -
}

# 验证配置文件
validate_config() {
    echo_step "验证配置文件..."

    if [ ! -f "${VALUES_FILE}" ]; then
        echo_error "配置文件不存在: ${VALUES_FILE}"
        exit 1
    fi

    # 检查必要配置 - 外部依赖必须填写
    for field in "external.database.host" "external.redis.host" "external.minio.endpoint" "external.rabbitmq.host"; do
        if grep -q "${field}: \"\"" "${VALUES_FILE}" || grep -q "${field}: ''" "${VALUES_FILE}"; then
            echo_error "请在 values.yaml 中配置 ${field}"
            exit 1
        fi
    done

    echo_info "配置文件验证通过"
}

# 渲染模板(用于调试)
render_templates() {
    echo_step "渲染 Helm 模板..."
    helm template ${RELEASE_NAME} "${CHART_PATH}" -n ${NAMESPACE} -f "${VALUES_FILE}" > /tmp/rendered-merged.yaml
    echo_info "模板已渲染到: /tmp/rendered-merged.yaml"
}

# 安装或升级
install_or_upgrade() {
    echo_step "部署服务..."

    # 检查是否已存在 release
    if helm status ${RELEASE_NAME} -n ${NAMESPACE} &> /dev/null; then
        echo_info "检测到已存在的 release,执行升级..."
        helm upgrade ${RELEASE_NAME} "${CHART_PATH}" \
            --namespace "${NAMESPACE}" \
            --values "${VALUES_FILE}" \
            --timeout 10m
    else
        echo_info "执行全新安装..."
        helm install "${RELEASE_NAME}" "${CHART_PATH}" \
            --namespace "${NAMESPACE}" \
            --values "${VALUES_FILE}" \
            --timeout 10m \
            --create-namespace
    fi

    echo_info "部署完成!"
}

# 等待 Pod 就绪
wait_for_pods() {
    echo_step "等待 Pod 就绪..."
    
    echo_info "等待 Media Suite Pod (包含 WVP + ZLM + ZLM-OSS)..."
    kubectl wait --for=condition=ready pod \
        -l app=media-suite \
        -n "${NAMESPACE}" \
        --timeout=600s || {
        echo_warn "Media Suite Pod 可能未就绪,请手动检查"
    }

    echo_info "等待其他服务 Pod..."
    kubectl wait --for=condition=ready pod \
        -l release="${RELEASE_NAME}" \
        -n "${NAMESPACE}" \
        --timeout=300s || {
        echo_warn "部分 Pod 可能未就绪,请手动检查"
    }
}

# 显示状态
show_status() {
    echo_step "服务状态:"
    echo ""
    helm status "${RELEASE_NAME}" -n "${NAMESPACE}"
    echo ""
    echo_info "Pod 列表:"
    kubectl get pods -n "${NAMESPACE}" -l release="${RELEASE_NAME}"
    echo ""
    echo_info "Service 列表:"
    kubectl get svc -n "${NAMESPACE}" -l release="${RELEASE_NAME}"
    echo ""
    
    # 获取节点 IP
    NODE_IP=$(kubectl get nodes -o jsonpath='{.items[0].status.addresses[?(@.type=="InternalIP")].address}' 2>/dev/null || echo "<NODE_IP>")
    
    echo ""
    echo_info "========================================="
    echo_info "服务访问地址"
    echo_info "========================================="
    echo_info "Media Suite (HostNetwork 模式):"
    echo "  WVP HTTP:    http://${NODE_IP}:$(grep 'http:' "${VALUES_FILE}" | head -1 | awk '{print $2}')"
    echo "  WVP SIP:     ${NODE_IP}:$(grep 'sip:' "${VALUES_FILE}" | head -1 | awk '{print $2}')/UDP"
    echo "  ZLM HTTP:    http://${NODE_IP}:$(grep 'http:' "${VALUES_FILE}" | head -1 | awk '{print $2}')"
    echo "  ZLM RTMP:    rtmp://${NODE_IP}:$(grep 'rtmp:' "${VALUES_FILE}" | head -1 | awk '{print $2}')"
    echo "  ZLM RTSP:    rtsp://${NODE_IP}:$(grep 'rtsp:' "${VALUES_FILE}" | head -1 | awk '{print $2}')"
    echo "  ZLM-OSS:     http://${NODE_IP}:$(grep 'port:' "${VALUES_FILE}" | grep -A1 'zlmOss' | tail -1 | awk '{print $2}')"
    echo ""
    echo_info "其他服务 (NodePort 模式):"
    echo "  Live Operator: http://${NODE_IP}:$(grep 'liveOpNodePort' "${VALUES_FILE}" | awk '{print $2}')"
    echo "  Live Proxy:    http://${NODE_IP}:$(grep 'liveProxyNodePort' "${VALUES_FILE}" | awk '{print $2}')"
    echo "  Live Helper:   http://${NODE_IP}:$(grep 'liveHelperNodePort' "${VALUES_FILE}" | awk '{print $2}')"
}

# 显示日志查看命令
show_log_commands() {
    echo ""
    echo_info "========================================="
    echo_info "日志查看命令"
    echo_info "========================================="
    echo_info "Media Suite 容器日志:"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-media-suite -n ${NAMESPACE} -c wvp"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-media-suite -n ${NAMESPACE} -c zlm"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-media-suite -n ${NAMESPACE} -c zlm-oss"
    echo ""
    echo_info "其他服务日志:"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-live-op -n ${NAMESPACE}"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-live-proxy -n ${NAMESPACE}"
    echo "  kubectl logs -f deployment/${RELEASE_NAME}-live-helper -n ${NAMESPACE}"
}

# 显示卸载命令
show_uninstall_command() {
    echo ""
    echo_info "========================================="
    echo_info "卸载命令"
    echo_info "========================================="
    echo "  helm uninstall ${RELEASE_NAME} -n ${NAMESPACE}"
}

# 主函数
main() {
    echo_info "========================================="
    echo_info "CMII Live Services (Merged) Helm 部署"
    echo_info "WVP + ZLM + ZLM-OSS 合并部署模式"
    echo_info "========================================="
    echo ""
    
    check_prerequisites
    validate_config
    create_namespace
    install_or_upgrade
    wait_for_pods
    show_status
    show_log_commands
    show_uninstall_command
    
    echo ""
    echo_info "========================================="
    echo_info "部署完成!"
    echo_info "========================================="
}

# 执行主函数
main "$@"
