#!/bin/bash
# 并发请求工具 - 持续并发访问指定域名，直到手动停止

# 颜色定义
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
CYAN='\033[1;36m'
NC='\033[0m' # 无颜色

# 显示标题
clear
echo -e "${CYAN}=============================================${NC}"
echo -e "${CYAN}       MT管理器 - 并发请求工具${NC}"
echo -e "${CYAN}=============================================${NC}"
echo ""

# 检查是否安装了curl
if ! command -v curl &> /dev/null; then
    echo -e "${RED}错误：未找到curl命令${NC}"
    echo "请在MT管理器终端中执行："
    echo "pkg install curl -y"
    exit 1
fi

# 输入域名
read -p "请输入目标域名（例如：https://example.com）：" domain

# 验证域名格式
if [[ -z "$domain" ]]; then
    echo -e "${RED}错误：域名不能为空${NC}"
    exit 1
fi

# 确保域名有协议头
if [[ ! "$domain" =~ ^https?:// ]]; then
    domain="http://$domain"
    echo -e "${YELLOW}提示：自动添加协议头 -> ${domain}${NC}"
fi

# 输入间隔毫秒
read -p "请输入请求间隔（毫秒，默认1000）：" interval
interval=${interval:-1000}

# 转换为秒
interval_sec=$(echo "scale=3; $interval / 1000" | bc)

# 输入并发数
read -p "请输入并发线程数（默认5）：" threads
threads=${threads:-5}

# 输入总请求次数（0表示无限）
read -p "请输入总请求次数（0表示无限，默认0）：" total_requests
total_requests=${total_requests:-0}

# 显示配置信息
echo ""
echo -e "${GREEN}=============================================${NC}"
echo -e "${GREEN}配置信息：${NC}"
echo -e "目标域名：${CYAN}$domain${NC}"
echo -e "请求间隔：${YELLOW}${interval}毫秒（${interval_sec}秒）${NC}"
echo -e "并发线程：${YELLOW}${threads}个${NC}"
echo -e "请求次数：${YELLOW}$([ "$total_requests" -eq 0 ] && echo "无限" || echo "$total_requests")${NC}"
echo -e "${GREEN}=============================================${NC}"
echo ""

# 统计变量
success_count=0
fail_count=0
total_count=0
start_time=$(date +%s)

# 创建临时目录存储进程信息
tmp_dir="/data/local/tmp/concurrent_requests_$$"
mkdir -p "$tmp_dir"

# 清理函数
cleanup() {
    echo -e "\n${YELLOW}正在停止所有并发进程...${NC}"
    
    # 杀死所有子进程
    if [[ -f "${tmp_dir}/pids" ]]; then
        while read pid; do
            kill -9 "$pid" 2>/dev/null
        done < "${tmp_dir}/pids"
    fi
    
    # 删除临时文件
    rm -rf "$tmp_dir"
    
    # 显示统计信息
    end_time=$(date +%s)
    duration=$((end_time - start_time))
    
    echo -e "\n${CYAN}============== 统计信息 ==============${NC}"
    echo -e "运行时间：${duration}秒"
    echo -e "总请求数：${total_count}"
    echo -e "成功请求：${GREEN}${success_count}${NC}"
    echo -e "失败请求：${RED}${fail_count}${NC}"
    if [ $total_count -gt 0 ]; then
        success_rate=$(echo "scale=2; $success_count * 100 / $total_count" | bc)
        echo -e "成功率：${YELLOW}${success_rate}%${NC}"
    fi
    echo -e "平均QPS：${YELLOW}$(echo "scale=2; $total_count / $duration" | bc)${NC}"
    echo -e "${CYAN}======================================${NC}"
    echo -e "${GREEN}并发请求已停止${NC}"
    exit 0
}

# 设置退出信号处理
trap cleanup INT TERM EXIT

# 单个请求函数
make_request() {
    local thread_id=$1
    local request_num=0
    
    while true; do
        # 如果设置了总请求数限制
        if [ $total_requests -gt 0 ]; then
            if [ $total_count -ge $total_requests ]; then
                break
            fi
        fi
        
        request_num=$((request_num + 1))
        current_total=$((total_count + 1))
        
        echo -e "[$(date '+%H:%M:%S')] ${BLUE}线程${thread_id}${NC} 请求 ${YELLOW}${request_num}${NC} 总请求 ${CYAN}${current_total}${NC}"
        
        # 发送请求
        response=$(curl -s -o /dev/null -w "%{http_code} %{time_total}" --connect-timeout 10 --max-time 30 "$domain" 2>&1)
        
        # 更新统计
        total_count=$((total_count + 1))
        
        if [[ "$response" =~ ^2[0-9][0-9] ]] || [[ "$response" =~ ^3[0-9][0-9] ]]; then
            success_count=$((success_count + 1))
            http_code=$(echo "$response" | awk '{print $1}')
            response_time=$(echo "$response" | awk '{print $2}')
            echo -e "  ${GREEN}✓ 成功${NC} HTTP: ${http_code} 耗时: ${response_time}s"
        else
            fail_count=$((fail_count + 1))
            echo -e "  ${RED}✗ 失败${NC} 响应: $response"
        fi
        
        # 等待指定间隔
        sleep $interval_sec
    done
}

# 启动并发请求
echo -e "${GREEN}开始并发请求...${NC}"
echo -e "${YELLOW}按 Ctrl+C 停止${NC}"
echo ""

# 存储所有进程PID
pids_file="${tmp_dir}/pids"
> "$pids_file"

# 启动所有线程
for ((i=1; i<=$threads; i++)); do
    make_request $i &
    echo $! >> "$pids_file"
done

# 等待所有进程
wait

# 如果是因为请求数限制而退出
if [ $total_requests -gt 0 ] && [ $total_count -ge $total_requests ]; then
    echo -e "\n${GREEN}已完成指定的 ${total_requests} 次请求${NC}"
    cleanup
fi