#!/bin/bash
################################################################################
# 50_system_profile.sh — 系统类型识别
# 功能: 检测平台类型(新/旧)、容器类型(ujava/upython/upython_voice)、ujava变体
# 参考: ServerProfile.psm1（PowerShell 移植）
# 日期: 2026-07-22
################################################################################

# 获取脚本所在目录并加载依赖
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIB_DIR="${LIB_DIR:-/tmp/check_modules}"

# 加载配置文件和通用函数库
if [ -f "$LIB_DIR/lib/config.sh" ]; then
    source "$LIB_DIR/lib/config.sh"
else
    echo "ERROR: 配置文件不存在: $LIB_DIR/lib/config.sh"
    exit 1
fi

if [ -f "$LIB_DIR/lib/common.sh" ]; then
    source "$LIB_DIR/lib/common.sh"
else
    echo "ERROR: 通用函数库不存在: $LIB_DIR/lib/common.sh"
    exit 1
fi

# ==================== 平台类型检测 ====================

detect_platform_type() {
    # 新统一平台：存在 /data/services 目录
    if [ -d "/data/services" ]; then
        output_result "SYS_PROFILE_PLATFORM_TYPE" "new"
    else
        output_result "SYS_PROFILE_PLATFORM_TYPE" "old"
    fi
    output_result "SYS_PROFILE_PLATFORM_TYPE_LEVEL" "正常"
}

# ==================== 容器类型检测 ====================

detect_container_type() {
    local containers
    containers=$(docker ps --format '{{.Names}}' 2>/dev/null)

    # 注意匹配顺序：upython_voice 须在 upython 之前，否则 upython 会先匹配
    if echo "$containers" | grep -qE '^ujava[0-9]*$'; then
        output_result "SYS_PROFILE_CONTAINER_TYPE" "ujava"
    elif echo "$containers" | grep -qE '^upython_voice[0-9]*$'; then
        output_result "SYS_PROFILE_CONTAINER_TYPE" "upython_voice"
    elif echo "$containers" | grep -qE '^upython[0-9]*$'; then
        output_result "SYS_PROFILE_CONTAINER_TYPE" "upython"
    else
        output_result "SYS_PROFILE_CONTAINER_TYPE" "unknown"
    fi
    output_result "SYS_PROFILE_CONTAINER_TYPE_LEVEL" "正常"
}

# ==================== ujava 变体检测 ====================

detect_ujava_variant() {
    # 仅 ujava 容器有效：通过目录区分 unified / meeting
    local ujava_container
    ujava_container=$(docker ps --format '{{.Names}}' 2>/dev/null | grep -E '^ujava[0-9]*$' | head -1)

    if [ -n "$ujava_container" ]; then
        if [ -d "/var/www/java/unifiedPlatform" ]; then
            output_result "SYS_PROFILE_UJAVA_VARIANT" "unified"
        else
            output_result "SYS_PROFILE_UJAVA_VARIANT" "meeting"
        fi
    else
        output_result "SYS_PROFILE_UJAVA_VARIANT" "none"
    fi
    output_result "SYS_PROFILE_UJAVA_VARIANT_LEVEL" "正常"
}

# ==================== 主检测流程 ====================

main() {
    log_info "开始系统类型识别..."

    set +e

    detect_platform_type 2>/dev/null || true
    detect_container_type 2>/dev/null || true
    detect_ujava_variant 2>/dev/null || true

    log_info "系统类型识别完成"
}

main
