#!/bin/bash
# batch_deploy.sh — 批量部署 Agent v3.1 到多台 Android 设备
#
# 用法：
#   ./scripts/batch_deploy.sh --server ws://IP:8899/ws/device
#   ./scripts/batch_deploy.sh --server ws://IP:8899/ws/device --ai-url http://IP:3102 --ai-key KEY
#   ./scripts/batch_deploy.sh --devices "serial1,serial2,serial3" --server ws://...
#
# 前置：所有目标设备已通过 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'
info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SDK_ROOT="$(dirname "$SCRIPT_DIR")"
AGENT_DIR="$SDK_ROOT/agent"
SERVER_URL=""
DEVICE_LIST=""
AI_URL=""
AI_KEY=""
INSTALL_FRIDA="false"
RESULTS=()

while [[ $# -gt 0 ]]; do
    case "$1" in
        --server|-s)   SERVER_URL="$2"; shift 2 ;;
        --devices|-d)  DEVICE_LIST="$2"; shift 2 ;;
        --ai-url)      AI_URL="$2"; shift 2 ;;
        --ai-key)      AI_KEY="$2"; shift 2 ;;
        --frida)       INSTALL_FRIDA="true"; shift ;;
        --help|-h)
            echo "用法: bash batch_deploy.sh --server ws://IP:8899/ws/device [选项]"
            echo ""
            echo "  --server, -s    SDK 服务器 WebSocket 地址（必填）"
            echo "  --devices, -d   设备序列号（逗号分隔），不填则自动检测全部"
            echo "  --ai-url        AI Brain API 地址"
            echo "  --ai-key        AI Brain API Key"
            echo "  --frida         同时部署 Frida Server"
            exit 0 ;;
        *) shift ;;
    esac
done

if [[ -z "$SERVER_URL" ]]; then
    error "缺少 --server 参数"; exit 1
fi

if ! command -v adb &>/dev/null; then
    error "adb 未安装"; exit 1
fi

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

if [[ ${#DEVICES[@]} -eq 0 ]]; then
    error "未检测到 ADB 设备"; exit 1
fi

echo ""
echo -e "${BOLD}${CYAN}============================================${NC}"
echo -e "${BOLD}${CYAN}  批量部署 Agent v3.1 (${#DEVICES[@]} 台设备)${NC}"
echo -e "${BOLD}${CYAN}============================================${NC}"
echo ""

deploy_one() {
    local serial="$1"
    local idx="$2"
    local total="$3"
    echo ""
    info "[$idx/$total] 部署到 $serial ..."

    if ! adb -s "$serial" shell echo ok &>/dev/null; then
        warn "[$serial] 设备不可达，跳过"
        RESULTS+=("$serial FAIL(不可达)")
        return
    fi

    local brand; brand=$(adb -s "$serial" shell getprop ro.product.brand 2>/dev/null || echo "unknown")
    local model; model=$(adb -s "$serial" shell getprop ro.product.model 2>/dev/null || echo "unknown")
    info "[$serial] $brand $model"

    local has_termux; has_termux=$(adb -s "$serial" shell pm list packages com.termux 2>/dev/null || echo "")
    if [[ -z "$has_termux" || "$has_termux" != *"com.termux"* ]]; then
        warn "[$serial] Termux 未安装，跳过（请先安装 Termux）"
        RESULTS+=("$serial FAIL(无Termux)")
        return
    fi

    info "[$serial] 打包 Agent 代码..."
    local tmp_tar="/tmp/agent_deploy_${serial}.tar.gz"
    tar czf "$tmp_tar" -C "$AGENT_DIR" \
        agent.py ai_brain.py skill_executor.py skill_bus.py error_handler.py \
        vision_helper.py voice_agent.py config.json.example \
        skills/ hook/ hawk/ 2>/dev/null || {
        tar czf "$tmp_tar" -C "$AGENT_DIR" agent.py skill_executor.py skills/ 2>/dev/null
    }

    info "[$serial] 推送文件..."
    adb -s "$serial" push "$tmp_tar" /sdcard/agent_deploy.tar.gz 2>/dev/null

    info "[$serial] 解压并安装..."
    adb -s "$serial" shell "run-as com.termux mkdir -p /data/data/com.termux/files/home/workphone-agent 2>/dev/null || true"
    adb -s "$serial" shell "
        cd /sdcard && \
        cp agent_deploy.tar.gz /data/local/tmp/ 2>/dev/null; \
        su -c 'cd /data/local/tmp && tar xzf agent_deploy.tar.gz -C /data/data/com.termux/files/home/workphone-agent/' 2>/dev/null || \
        echo 'fallback' \
    " 2>/dev/null || true

    info "[$serial] 生成配置..."
    local ai_block=""
    if [[ -n "$AI_URL" ]]; then
        ai_block=",\"ai_brain\":{\"enabled\":true,\"api_url\":\"$AI_URL\",\"api_key\":\"$AI_KEY\",\"model\":\"auto\",\"brain_interval\":60,\"standing_orders\":[\"检查微信未读消息\",\"自动通过好友请求\",\"保活微信\"]}"
    fi
    local config="{\"device_id\":\"$serial\",\"server_url\":\"$SERVER_URL\",\"heartbeat_interval\":10,\"project_id\":\"cunkebao\"$ai_block}"
    adb -s "$serial" shell "echo '$config' > /data/local/tmp/wp_config.json" 2>/dev/null

    if [[ "$INSTALL_FRIDA" == "true" ]]; then
        info "[$serial] 安装 Frida Server..."
        bash "$SCRIPT_DIR/setup_frida.sh" "$serial" 2>/dev/null || warn "[$serial] Frida 安装失败"
    fi

    rm -f "$tmp_tar"
    info "[$serial] ✅ 部署完成"
    RESULTS+=("$serial OK ($brand $model)")
}

idx=0
for serial in "${DEVICES[@]}"; do
    idx=$((idx + 1))
    deploy_one "$serial" "$idx" "${#DEVICES[@]}"
done

echo ""
echo -e "${BOLD}${CYAN}============================================${NC}"
echo -e "${BOLD}${GREEN}  批量部署结果${NC}"
echo -e "${BOLD}${CYAN}============================================${NC}"
for r in "${RESULTS[@]}"; do
    echo "  $r"
done
ok_count=$(printf '%s\n' "${RESULTS[@]}" | grep -c "OK" || true)
echo ""
echo -e "  成功: ${GREEN}${ok_count}${NC} / ${#DEVICES[@]}"
echo -e "${BOLD}${CYAN}============================================${NC}"
