#!/bin/bash
# test_startup_time.sh
# 测试应用启动时间

PACKAGE_NAME="${1:-com.example.app}"
MAIN_ACTIVITY="${2}"
ITERATIONS="${3:-10}"

if [ -z "$MAIN_ACTIVITY" ]; then
    # 尝试从包名推断主Activity
    MAIN_ACTIVITY="${PACKAGE_NAME}/.MainActivity"
fi

echo "Testing startup time for $PACKAGE_NAME"
echo "Main Activity: $MAIN_ACTIVITY"
echo "Iterations: $ITERATIONS"
echo ""

total_time=0
min_time=999999
max_time=0
times=()

for i in $(seq 1 $ITERATIONS); do
    # 停止应用
    adb shell am force-stop "$PACKAGE_NAME" > /dev/null 2>&1
    sleep 1
    
    # 启动应用并测量时间
    result=$(adb shell am start -W -n "$MAIN_ACTIVITY" 2>/dev/null)
    
    if [ $? -ne 0 ]; then
        echo "Iteration $i: Failed to start"
        continue
    fi
    
    # 提取TotalTime
    time=$(echo "$result" | grep "TotalTime" | awk '{print $2}')
    
    if [ -z "$time" ]; then
        echo "Iteration $i: Could not get time"
        continue
    fi
    
    echo "Iteration $i: ${time}ms"
    
    times+=($time)
    total_time=$((total_time + time))
    
    if [ $time -lt $min_time ]; then
        min_time=$time
    fi
    
    if [ $time -gt $max_time ]; then
        max_time=$time
    fi
    
    sleep 2
done

if [ ${#times[@]} -eq 0 ]; then
    echo "No successful iterations!"
    exit 1
fi

average=$((total_time / ${#times[@]}))
echo ""
echo "========================================="
echo "Results:"
echo "  Successful iterations: ${#times[@]}"
echo "  Average: ${average}ms"
echo "  Min: ${min_time}ms"
echo "  Max: ${max_time}ms"
echo "========================================="
