bang w#!/bin/bash
#
# QSJNIC v1.0.0-beta6 车机部署与验证脚本
# 适用: 支持 adb root + remount 的 userdebug/eng 车机
# 目标 IP: 192.168.0.66
#

set -euo pipefail

TARGET_IP="192.168.0.66"
RELEASE_DIR="$(cd "$(dirname "$0")/../release/v1.0.0-beta6" && pwd)"
SERVICE_APK="${RELEASE_DIR}/qsmw-service.apk"
DEMO_OTA="${RELEASE_DIR}/qsmw-ota-demo.apk"
DEMO_RADIO="${RELEASE_DIR}/qsmw-radio-demo.apk"
DEMO_VEHICLE="${RELEASE_DIR}/qsmw-vehicle-demo.apk"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }

# ----------------------- 前置检查 -----------------------
info "检查 release 产物..."
for f in "$SERVICE_APK" "$DEMO_OTA" "$DEMO_RADIO" "$DEMO_VEHICLE"; do
    if [[ ! -f "$f" ]]; then
        error "文件不存在: $f"
        exit 1
    fi
done
info "release 产物齐全"

info "连接车机 ${TARGET_IP}..."
adb connect "${TARGET_IP}" >/dev/null 2>&1 || true
adb -s "${TARGET_IP}:5555" wait-for-device

DEVICE_STATUS=$(adb -s "${TARGET_IP}:5555" get-state)
if [[ "$DEVICE_STATUS" != "device" ]]; then
    error "adb 状态异常: ${DEVICE_STATUS}"
    exit 1
fi
info "adb 已连接: ${TARGET_IP}"

# ----------------------- 提权 & remount -----------------------
info "执行 adb root..."
adb -s "${TARGET_IP}:5555" root >/dev/null 2>&1
sleep 2
adb -s "${TARGET_IP}:5555" wait-for-device

info "执行 adb remount..."
if ! adb -s "${TARGET_IP}:5555" remount >/dev/null 2>&1; then
    error "remount 失败，该车机可能不支持写入 /system 分区"
    error "请确认是 userdebug/eng 版本，或已执行 'adb disable-verity' 并重启"
    exit 1
fi
info "remount 成功"

# ----------------------- 部署 Service -----------------------
info "部署 qsmw-service.apk 到 /system/priv-app/QsmwService/..."
adb -s "${TARGET_IP}:5555" shell "mkdir -p /system/priv-app/QsmwService"

# 如果已存在旧版本，先备份（可选）
OLD_APK=$(adb -s "${TARGET_IP}:5555" shell "ls /system/priv-app/QsmwService/*.apk 2>/dev/null" | tr -d '\r')
if [[ -n "$OLD_APK" ]]; then
    warn "发现旧版本: ${OLD_APK}，正在替换..."
    adb -s "${TARGET_IP}:5555" shell "rm -f ${OLD_APK}"
fi

adb -s "${TARGET_IP}:5555" push "${SERVICE_APK}" /system/priv-app/QsmwService/qsmw-service.apk
adb -s "${TARGET_IP}:5555" shell "chmod 644 /system/priv-app/QsmwService/qsmw-service.apk"
info "Service 部署完成"

# ----------------------- 安装 Demo (user 0) -----------------------
install_demo() {
    local apk_path="$1"
    local pkg_name="$2"
    local demo_name="$3"

    info "安装 ${demo_name}..."
    
    # 如果已安装，先卸载
    if adb -s "${TARGET_IP}:5555" shell "pm list packages --user 0 ${pkg_name}" | grep -q "${pkg_name}"; then
        warn "${pkg_name} 已存在于 user 0，先卸载旧版本..."
        adb -s "${TARGET_IP}:5555" shell "pm uninstall --user 0 ${pkg_name}" >/dev/null 2>&1 || true
    fi

    adb -s "${TARGET_IP}:5555" install -r --user 0 "${apk_path}"
    info "${demo_name} 安装完成"
}

install_demo "${DEMO_OTA}"     "com.qsjnic.demo.ota"     "OTA Demo"
install_demo "${DEMO_RADIO}"   "com.qsjnic.demo.radio"   "Radio Demo"
install_demo "${DEMO_VEHICLE}" "com.qsjnic.demo.vehicle" "Vehicle Demo"

# ----------------------- 重启 -----------------------
warn "即将重启车机以加载系统级 Service..."
sleep 2
adb -s "${TARGET_IP}:5555" reboot

info "已发送重启指令，等待设备重新上线..."
sleep 10
adb -s "${TARGET_IP}:5555" wait-for-device
info "车机已重新上线"

# ----------------------- 验证阶段 -----------------------
info "========== 开始验证 =========="

# 1. 校验包版本
info "[验证1/6] 检查 Service 包信息..."
adb -s "${TARGET_IP}:5555" shell "dumpsys package com.qsjnic.mcu.service | grep -E 'versionCode|versionName'" || {
    error "无法获取 Service 包信息，可能未正确安装"
    exit 1
}

# 2. 校验预置路径
info "[验证2/6] 检查预置路径..."
adb -s "${TARGET_IP}:5555" shell "ls -lZ /system/priv-app/QsmwService/"

# 3. 校验权限声明
info "[验证3/6] 检查权限声明..."
adb -s "${TARGET_IP}:5555" shell "dumpsys package com.qsjnic.mcu.service | grep -A2 'cn.qsjnic.permission.MCU_ACCESS'" || warn "未找到权限声明（可能不影响）"

# 4. 检查 demo 是否在 user 0
info "[验证4/6] 检查 Demo 应用安装状态（user 0）..."
for pkg in com.qsjnic.demo.ota com.qsjnic.demo.radio com.qsjnic.demo.vehicle; do
    if adb -s "${TARGET_IP}:5555" shell "pm list packages --user 0 ${pkg}" | grep -q "${pkg}"; then
        info "  ✓ ${pkg}"
    else
        error "  ✗ ${pkg} 未安装"
    fi
done

# 5. 检查服务是否运行
info "[验证5/6] 检查服务进程..."
adb -s "${TARGET_IP}:5555" shell "ps -A | grep -E 'qsjnic|mcu' || echo '(暂无进程，可能尚未自启)'"

# 6. 抓取相关日志
info "[验证6/6] 抓取最近 30 秒 Mcu 相关日志..."
adb -s "${TARGET_IP}:5555" logcat -d -t 30s --pid=$(adb -s "${TARGET_IP}:5555" shell "pidof com.qsjnic.mcu.service 2>/dev/null || echo ''") 2>/dev/null | tail -20 || {
    adb -s "${TARGET_IP}:5555" logcat -d -t 30s | grep -iE 'QsMcuSystemService|McuLink|qsjnic' | tail -20 || true
}

info "========== 部署与验证完成 =========="
echo ""
echo "手动测试建议:"
echo "  1. 打开 Vehicle Demo 验证车辆信息/Key 域方控接口"
echo "  2. 打开 Radio Demo 验证收音机接口"
echo "  3. 打开 OTA Demo 验证 OTA 升级接口"
echo "  4. 实时观察日志: adb -s ${TARGET_IP}:5555 logcat | grep -iE 'QsMcuSystemService|McuLink|qsjnic'"
echo ""
echo "注意: 当前 APK 使用 sim.jks (debug) 签名，非 platform 签名。"
echo "      如遇到 SELinux 拒绝或 system_app 权限不足，请联系系统工程师确认:"
echo "      - /dev/ttyS7 的权限和 SELinux 标签"
echo "      - 是否需要使用 platform 签名重新签名"
