#!/bin/bash
################################################################################
# 57_android_check.sh — Android 设备检测
# 功能: 检测 adb 可用性、设备连接状态
# 参考: AndroidCheck.psm1
# 日期: 2026-07-22
# 说明: 只检测不操作，检查 ADB 服务和设备连接状态
################################################################################

# 获取脚本所在目录并加载依赖
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

# ==================== ADB 工具检测 ====================

check_adb_available() {
    local adb_path=""
    local adb_ok="no"

    # 1. 检查系统 PATH 中的 adb
    if command -v adb >/dev/null 2>&1; then
        adb_path=$(command -v adb)
        adb_ok="yes"
    fi

    # 2. 检查常见安装位置
    if [ "$adb_ok" = "no" ]; then
        local adb_dirs=(
            "/usr/local/bin/adb"
            "/usr/bin/adb"
            "/opt/android-sdk/platform-tools/adb"
            "$HOME/Android/Sdk/platform-tools/adb"
            "/data/tools/adb"
        )
        for dir in "${adb_dirs[@]}"; do
            if [ -x "$dir" ]; then
                adb_path="$dir"
                adb_ok="yes"
                break
            fi
        done
    fi

    output_result "ANDROID_ADB_EXISTS" "$adb_ok"
    output_result "ANDROID_ADB_PATH" "${adb_path:-未找到}"

    if [ "$adb_ok" = "yes" ]; then
        # 获取 adb 版本
        local adb_version
        adb_version=$(adb version 2>/dev/null | head -1 || echo "未知")
        output_result "ANDROID_ADB_VERSION" "$adb_version"
        output_result "ANDROID_ADB_LEVEL" "正常"
    else
        output_result "ANDROID_ADB_VERSION" "未安装"
        output_result "ANDROID_ADB_LEVEL" "警告"
    fi

    ANDROID_ADB_OK="$adb_ok"
}

# ==================== ADB 服务状态检测 ====================

check_adb_server() {
    if [ "$ANDROID_ADB_OK" != "yes" ]; then
        output_result "ANDROID_SERVER_STATUS" "ADB未安装"
        output_result "ANDROID_SERVER_LEVEL" "警告"
        return
    fi

    local server_running="no"

    # 检查 adb server 是否运行
    if pgrep -f "adb server" >/dev/null 2>&1 || pgrep -x "adb" >/dev/null 2>&1; then
        server_running="yes"
    fi

    # 尝试启动 server（仅检测，不持续运行）
    adb start-server >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        server_running="yes"
    fi

    output_result "ANDROID_SERVER_STATUS" "$server_running"
    if [ "$server_running" = "yes" ]; then
        output_result "ANDROID_SERVER_LEVEL" "正常"
    else
        output_result "ANDROID_SERVER_LEVEL" "警告"
    fi
}

# ==================== 设备连接检测 ====================

check_connected_devices() {
    if [ "$ANDROID_ADB_OK" != "yes" ]; then
        output_result "ANDROID_DEVICE_COUNT" "0"
        output_result "ANDROID_DEVICE_LIST" "[]"
        output_result "ANDROID_DEVICE_LEVEL" "警告"
        return
    fi

    local device_count=0
    local device_list=""

    # 获取设备列表
    local devices_output
    devices_output=$(adb devices 2>/dev/null | grep -v "List of devices" | grep -v "^$" || echo "")

    if [ -n "$devices_output" ]; then
        while IFS= read -r line; do
            local device_id device_status
            device_id=$(echo "$line" | awk '{print $1}')
            device_status=$(echo "$line" | awk '{print $2}')

            if [ -n "$device_id" ] && [ "$device_id" != "daemon" ]; then
                device_count=$((device_count + 1))
                if [ -n "$device_list" ]; then
                    device_list="${device_list},"
                fi
                device_list="${device_list}{\"id\":\"${device_id}\",\"status\":\"${device_status}\"}"
            fi
        done <<< "$devices_output"
    fi

    output_result "ANDROID_DEVICE_COUNT" "$device_count"
    output_result "ANDROID_DEVICE_LIST" "[${device_list}]"

    if [ "$device_count" -gt 0 ]; then
        output_result "ANDROID_DEVICE_LEVEL" "正常"
    else
        output_result "ANDROID_DEVICE_LEVEL" "警告"
    fi
}

# ==================== 网络设备连接能力检测 ====================

check_network_adb_capability() {
    if [ "$ANDROID_ADB_OK" != "yes" ]; then
        output_result "ANDROID_NETWORK_CAPABLE" "no"
        output_result "ANDROID_NETWORK_LEVEL" "警告"
        return
    fi

    # 检查 adb 是否支持网络连接（tcpip）
    local network_capable="yes"

    # adb tcpip 命令存在性检查
    if adb help 2>/dev/null | grep -q "tcpip"; then
        network_capable="yes"
    fi

    output_result "ANDROID_NETWORK_CAPABLE" "$network_capable"
    output_result "ANDROID_NETWORK_LEVEL" "正常"
}

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

main() {
    log_info "开始 Android 设备检测..."

    set +e

    # 1. ADB 工具检测
    check_adb_available

    # 2. ADB 服务状态检测
    check_adb_server

    # 3. 已连接设备检测
    check_connected_devices

    # 4. 网络 ADB 能力检测
    check_network_adb_capability

    # 5. 综合状态
    if [ "$ANDROID_ADB_OK" = "yes" ]; then
        output_result "ANDROID_STATUS" "ADB已就绪"
        output_result "ANDROID_STATUS_LEVEL" "正常"
    else
        output_result "ANDROID_STATUS" "ADB未安装"
        output_result "ANDROID_STATUS_LEVEL" "警告"
    fi

    log_info "Android 设备检测完成"
}

main