#!/bin/bash
# ================================================================
#  AI数智员工 统一批量部署脚本 v4.0
# ================================================================
#
# 一键将 AI数智员工 统一 APK 部署到多台手机
# v4.0: 不再需要 Termux/Python Agent — 全部功能已内置于 APK
#
# 用法:
#   ./master_deploy.sh --server ws://IP:8899/ws/device
#   ./master_deploy.sh --server ws://IP:8899/ws/device --wifi-scan
#   ./master_deploy.sh --server ws://IP:8899/ws/device --devices "serial1,serial2"
#
# 前置: adb 已安装, 设备已通过 USB 或 WiFi ADB 连接
# ================================================================

set -eo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[0;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
APK_PATH="${PROJECT_ROOT}/android-app/app/build/outputs/apk/debug/app-debug.apk"
PACKAGE_NAME="com.system.cloudservice"
ACTIVITY_NAME=".ui.SetupActivity"

SERVER_URL=""
DEVICES=""
WIFI_SCAN=false
PROJECT_ID="cunkebao"

usage() {
    echo -e "${BOLD}AI数智员工 统一部署 v4.0${NC}"
    echo "用法: $0 --server <ws_url> [选项]"
    echo ""
    echo "选项:"
    echo "  --server URL      WebSocket 服务地址 (必填)"
    echo "  --project ID      项目 ID (默认: cunkebao)"
    echo "  --devices LIST    指定设备序列号 (逗号分隔)"
    echo "  --wifi-scan       WiFi ADB 扫描局域网"
    echo "  --apk PATH        指定 APK 路径"
    echo "  -h, --help        显示帮助"
}

while [[ $# -gt 0 ]]; do
    case $1 in
        --server) SERVER_URL="$2"; shift 2 ;;
        --project) PROJECT_ID="$2"; shift 2 ;;
        --devices) DEVICES="$2"; shift 2 ;;
        --wifi-scan) WIFI_SCAN=true; shift ;;
        --apk) APK_PATH="$2"; shift 2 ;;
        -h|--help) usage; exit 0 ;;
        *) echo -e "${RED}未知参数: $1${NC}"; usage; exit 1 ;;
    esac
done

if [[ -z "$SERVER_URL" ]]; then
    echo -e "${RED}错误: 必须指定 --server${NC}"
    usage
    exit 1
fi

# Check APK exists
if [[ ! -f "$APK_PATH" ]]; then
    echo -e "${YELLOW}APK 未找到: $APK_PATH${NC}"
    echo -e "${CYAN}正在构建...${NC}"
    cd "${PROJECT_ROOT}/android-app"
    ./gradlew assembleDebug --no-daemon
    if [[ ! -f "$APK_PATH" ]]; then
        echo -e "${RED}构建失败${NC}"
        exit 1
    fi
fi

echo -e "${GREEN}${BOLD}╔══════════════════════════════════════╗${NC}"
echo -e "${GREEN}${BOLD}║  AI数智员工 统一部署 v4.0             ║${NC}"
echo -e "${GREEN}${BOLD}╚══════════════════════════════════════╝${NC}"
echo -e "  APK:     $APK_PATH"
echo -e "  Server:  $SERVER_URL"
echo -e "  Project: $PROJECT_ID"
echo ""

# WiFi scan
if $WIFI_SCAN; then
    echo -e "${CYAN}扫描局域网 ADB 设备...${NC}"
    LOCAL_IP=$(ip route get 1 2>/dev/null | awk '{print $NF; exit}' || echo "192.168.1")
    SUBNET="${LOCAL_IP%.*}"
    for i in $(seq 1 254); do
        (adb connect "${SUBNET}.$i:5555" &>/dev/null &)
    done
    sleep 3
fi

# Get device list
if [[ -n "$DEVICES" ]]; then
    IFS=',' read -ra DEVICE_LIST <<< "$DEVICES"
else
    mapfile -t DEVICE_LIST < <(adb devices | grep -v "^$" | grep -v "^List" | awk '{print $1}')
fi

if [[ ${#DEVICE_LIST[@]} -eq 0 ]]; then
    echo -e "${RED}未发现设备${NC}"
    exit 1
fi

echo -e "${GREEN}发现 ${#DEVICE_LIST[@]} 台设备${NC}"
echo ""

deploy_device() {
    local serial="$1"
    local adb_cmd="adb -s $serial"
    
    echo -e "${CYAN}── 部署: $serial ──${NC}"
    
    # 1. Install APK
    echo -e "  安装 APK..."
    $adb_cmd install -r -g "$APK_PATH" 2>/dev/null || {
        echo -e "  ${RED}安装失败${NC}"
        return 1
    }
    echo -e "  ${GREEN}安装成功${NC}"
    
    # 2. Grant permissions
    echo -e "  授权..."
    for perm in CAMERA RECORD_AUDIO POST_NOTIFICATIONS SYSTEM_ALERT_WINDOW; do
        $adb_cmd shell pm grant "$PACKAGE_NAME" "android.permission.$perm" 2>/dev/null || true
    done
    
    # 3. Battery optimization whitelist
    $adb_cmd shell dumpsys deviceidle whitelist +$PACKAGE_NAME 2>/dev/null || true
    
    # 4. Launch app
    echo -e "  启动..."
    $adb_cmd shell am start -n "${PACKAGE_NAME}/${PACKAGE_NAME}${ACTIVITY_NAME}" 2>/dev/null || true
    
    echo -e "  ${GREEN}✅ 部署完成${NC}"
    echo ""
}

SUCCESS=0
FAIL=0

for device in "${DEVICE_LIST[@]}"; do
    device=$(echo "$device" | xargs)
    [[ -z "$device" ]] && continue
    if deploy_device "$device"; then
        ((SUCCESS++))
    else
        ((FAIL++))
    fi
done

echo -e "${BOLD}══════════════════════════════════════${NC}"
echo -e "${GREEN}成功: $SUCCESS${NC}  ${RED}失败: $FAIL${NC}  总计: ${#DEVICE_LIST[@]}"
echo ""
echo -e "${YELLOW}提示: 在手机上打开 APP → 扫码绑定 即可连接服务器${NC}"
echo -e "${YELLOW}      v4.0 无需安装 Termux / Python Agent${NC}"
