#!/bin/bash
# ─────────────────────────────────────────────────
# 工作手机 APK 一键编译 + 部署（全自动、零提问）
# 用法: ./deploy.sh [debug|release] [可选: 设备序列号]
# ─────────────────────────────────────────────────
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

# JDK：macOS 上**强制**优先 21/17，覆盖环境里指向 JDK 22+ 的 JAVA_HOME（Kotlin 1.9 守护进程会崩）
JAVA_HOME_FIXED=""
if [[ "${DEPLOY_USE_ENV_JAVA:-0}" != "1" && -x /usr/libexec/java_home ]]; then
    for _jv in 21 17; do
        if _jh="$(/usr/libexec/java_home -v "$_jv" 2>/dev/null)" && [[ -d "$_jh" ]]; then
            JAVA_HOME_FIXED="$_jh"
            break
        fi
    done
fi
if [[ -z "$JAVA_HOME_FIXED" && -d "/Library/Java/JavaVirtualMachines/temurin-21.jdk/Contents/Home" ]]; then
    JAVA_HOME_FIXED="/Library/Java/JavaVirtualMachines/temurin-21.jdk/Contents/Home"
fi
if [[ -n "$JAVA_HOME_FIXED" ]]; then
    export JAVA_HOME="$JAVA_HOME_FIXED"
elif [[ -n "${JAVA_HOME:-}" ]]; then
    export JAVA_HOME
elif [[ -x /usr/libexec/java_home ]]; then
    export JAVA_HOME="$(/usr/libexec/java_home 2>/dev/null || true)"
fi
if [[ -z "${JAVA_HOME:-}" || ! -d "$JAVA_HOME" ]]; then
    echo "✗ 未找到可用 JAVA_HOME（请安装 Temurin 21 或设 DEPLOY_USE_ENV_JAVA=1）"
    exit 1
fi

BUILD_TYPE="${1:-debug}"
SERIAL="${2:-}"

BUILD_CAP="$(tr '[:lower:]' '[:upper:]' <<< "${BUILD_TYPE:0:1}")${BUILD_TYPE:1}"
TASK="assemble${BUILD_CAP}"
APK_PATH="app/build/outputs/apk/${BUILD_TYPE}/app-${BUILD_TYPE}.apk"
PKG="com.system.cloudservice"

pick_adb_serial() {
    # 优先 USB 真机（排除 emulator），否则第一个 device
    local s
    s="$(adb devices | awk '/\tdevice$/ {print $1}' | grep -v '^emulator-' | head -1)"
    if [[ -z "$s" ]]; then
        s="$(adb devices | awk '/\tdevice$/ {print $1}' | head -1)"
    fi
    echo "$s"
}

ADB_ARGS=()
if [[ -n "$SERIAL" ]]; then
    ADB_ARGS=( -s "$SERIAL" )
else
    AUTO_SERIAL="$(pick_adb_serial)"
    if [[ -n "$AUTO_SERIAL" ]]; then
        ADB_ARGS=( -s "$AUTO_SERIAL" )
    fi
fi

echo "═══════════════════════════════════════"
echo "  工作手机 统一安装包部署（全自动）"
echo "  构建类型: ${BUILD_TYPE}"
echo "  设备序列号: ${SERIAL:-${AUTO_SERIAL:-（自动）}}"
echo "  JAVA_HOME: ${JAVA_HOME}"
echo "═══════════════════════════════════════"

echo ""
echo "▸ [1/5] 停止守护进程并清理本地缓存（防路径错乱/Kotlin JDK 不匹配）…"
if [[ "${DEPLOY_NO_CLEAN:-0}" != "1" ]]; then
    ./gradlew --stop 2>/dev/null || true
    rm -rf .gradle app/build
else
    ./gradlew --stop 2>/dev/null || true
fi

echo ""
echo "▸ [2/5] 编译..."
if ! ./gradlew "$TASK" --no-daemon -q; then
    echo "✗ Gradle 失败"
    exit 1
fi

if [[ ! -f "$APK_PATH" ]]; then
    echo "✗ APK 未找到: $APK_PATH"
    exit 1
fi
APK_SIZE=$(du -h "$APK_PATH" | cut -f1)
echo "  ✓ 编译完成 ($APK_SIZE)"

echo ""
echo "▸ [3/5] 检查设备..."
DEVICE_COUNT=$(adb "${ADB_ARGS[@]}" devices 2>/dev/null | grep -c $'\tdevice$' || true)
if [[ "$DEVICE_COUNT" -eq 0 ]]; then
    echo "✗ 未检测到设备（请 USB 调试 + 授权）"
    exit 1
fi
DEVICE_MODEL=$(adb "${ADB_ARGS[@]}" shell getprop ro.product.model 2>/dev/null | tr -d '\r')
echo "  ✓ 设备: $DEVICE_MODEL"

echo ""
echo "▸ [4/5] 安装..."
adb "${ADB_ARGS[@]}" shell am force-stop "$PKG" 2>/dev/null || true
adb "${ADB_ARGS[@]}" install -r -g -t "$APK_PATH" 2>&1

echo ""
echo "▸ [5/5] 启动（无桌面图标，仅显式启动）..."
adb "${ADB_ARGS[@]}" shell am start -n "${PKG}/.ui.SetupActivity" 2>/dev/null || true

echo ""
echo "═══════════════════════════════════════"
echo "  ✓ 部署完成! ($APK_SIZE)"
echo "═══════════════════════════════════════"
